* feat(roles): issueops.Heartbeater role on the dolt, embedded and uow legs
Adds issueops.Heartbeater.Heartbeat(HeartbeatRequest{Actor, IssueID}) ->
HeartbeatResult{IssueID, Holder, HeartbeatAt, LeaseExpiresAt, Rearmed},
the lease refresh behind `bd heartbeat`, as its own role with its own
accessor.
- One body: internal/storage/issueops.ExecuteHeartbeatInTx validates
(*HeartbeatFieldError for a blank/over-long actor or empty id), refuses
a wisp, then runs RenewLeaseInTx, which is HeartbeatIssueInTx's body
reporting the renewal. HeartbeatIssueInTx is now a wrapper, so the legacy
HeartbeatIssue legs answer the same text and sentinels.
- The refresh is fenced on the holder AND on the live claim: after the
holder-fenced UPDATE, a read in the same transaction requires the issue
to be in_progress under the holder (the `update leases set` prefix and
the one IF() the Postgres dialect rewrites are unchanged; a Postgres port
should expect more serialization retries from that read). A refusal deletes the caller's orphaned lease
row, and the legs commit that refusal.
- A refresh writes only the lease row: no row_lock, version, updated_at,
event, journal entry, Dolt commit or hook. A re-arm (a live hand-doled
claim with no lease row the caller holds) is recorded as a mutation:
row_lock reminted, updated_at stamped, a lease_rearmed event, a journal
entry, a version, a Dolt commit (LeaseRearmVersionCommit) and on_update.
The remint makes a re-arm collide with a racing release or close instead
of leaving an orphaned lease on an open or closed issue (a pre-existing
race on every Dolt route). Rearmed is true only when a row was created:
a same-second refresh (0 changed rows on embedded Dolt) or a holder
spelled differently refreshes the existing row in place and keeps its
granted_at/granted_node. Reported times are rounded to whole seconds,
the stored values; the binds stay unrounded so a same-second refresh is
never a 0-row UPDATE on Dolt.
- Typed refusals: an absent id is ErrNotFound; a foreign holder is
*LeaseConflictError{Holder} wrapping ErrAlreadyClaimed; a wisp
(Ephemeral) or no live claim is *LeaseConflictError wrapping the new
ErrLeaseNotHeld, which also matches ErrNotClaimable.
- Legs: DoltStore and EmbeddedDoltStore through the issue-operation
funnel (DOLT_ADD of the named tables, then DOLT_COMMIT -m, after the SQL
commit); uow.NewHeartbeater through the new uow.RunTxScoped: a refresh or
a refusal commits with the plain SQL COMMIT (no working-set scan, no Dolt
commit, nothing another writer left uncommitted is swept), and a re-arm
commits through the new ScopedCommitter (DOLT_ADD of exactly its tables,
DOLT_COMMIT -m, never -Am). The legacy HeartbeatIssue doors commit a
re-arm the same way and keep a refusal's orphan delete, and the
proxied-server `bd heartbeat` route runs the role's body with the same
scoped commit.
- Census: storage.Storage gains Heartbeater(); HookFiringStore wraps it
(fires on_update for a re-arm only, RoleFiresHooks knows it), telemetry
wraps it, httpapi.timedProvider, uow.notifyingProvider (records a re-arm)
and externaldeps.uowProvider build it; the journal and version guards
list the heartbeat family as entry points; the httpclient unsupported
shell is regenerated and Heartbeater sits on its unsupported allowlist
until the wire lands.
Conformance: RunHeartbeater* (18 cases) on dolt, embedded dolt and uow:
refresh post-state with the stored times pinned to the result; no
row_lock/current_revision/updated_at/events/journal/issue_versions/
version-control/hook change; a guarded write with the pre-heartbeat
revision still lands; foreign holder refused against an aged lease;
refused after close/release/reclaim/status move; wisp refused; hand-doled
claim re-armed as a mutation; same-second heartbeat is not a re-arm;
orphaned leases on released, closed and reassigned issues refused and
deleted; a refresh and a refusal against a dirty working set make no
commit and leave the other writer's change uncommitted, and a re-arm
commits only its own tables; absent id; request rules; no request mutation. The http leg is
waived until the wire lands.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(httpapi): POST /v0/beads/issues/{id}:heartbeat behind issues.heartbeat
Publishes issueops.Heartbeater on bd serve as heartbeatIssue, the served
lease refresh behind `bd heartbeat`.
- Spec: the operation, HeartbeatIssueRequest {actor} and
HeartbeatIssueResponse {id, holder, heartbeat_at, lease_expires_at,
rearmed}; no `revision` (a refresh writes nothing to the row) and no
expected_version (the fence is the holder and the live claim).
issues.heartbeat joins the capability vocabulary and lease_not_held
(409) the Problem.code list; `reason: ephemeral` qualifies it for a
wisp. apigen and the wire-shape golden are regenerated; the golden diff
is additive only, so wire_revision stays 2.
- Server: route row on the custom-method dispatcher, handleHeartbeat in
heartbeat.go (claim's actor rules via bodyActor, unknown member and
query refusals), Config.Heartbeater as a required role (sourceRoles,
roleSourceNames, the per-request uow.HeartbeaterSource accessor).
failHeartbeat maps *LeaseConflictError typed fields: a foreign holder
is the claim's conflict shape (already_claimed + assignee +
issue_status); no live claim, a wisp included, is the new
lease_not_held (+ issue_status, + reason: ephemeral for a wisp), matched
before the generic arms so ErrLeaseNotHeld's ErrNotClaimable never
surfaces as not_claimable. Its detail names the one state the refusing
transaction found (closed, open and not claimed, an ephemeral wisp, ...).
- bd serve wires the role from its peeled store (serveRoleSource gains
Heartbeater); the serve stub stores, the corpus and e2e harnesses, the
served harness and the encode oracle bind it.
- Wire client vocabulary: OpHeartbeatIssue/issues.heartbeat and
MethodHeartbeat are CLASSIFIED (the capability set-equality gate),
ReasonEphemeral is pinned to the server's, and lease_not_held rebuilds
*LeaseConflictError{Status, Ephemeral} wrapping ErrLeaseNotHeld in the
native words (the code-table set-equality gate). No accessor yet.
Tests: heartbeat_test.go (request mapping and projection, edge refusals,
every role refusal with its code, members and state-specific detail, the
code row, the capability). The served-http Heartbeater leg
(served_heartbeater_test.go, 18 cases) runs the contract against a real
bd serve through a test-local dial over the store's own dispatch, and the
http-leg waivers are deleted.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(http): bd heartbeat over http through httpclient.Heartbeater
The client leg of the served lease refresh, and `bd heartbeat` on the
role for every route.
- httpclient.Store.Heartbeater (heartbeater.go) dials POST
/v0/beads/issues/{id}:heartbeat through Store.dispatch, so
issues.heartbeat is preflighted: an older server is refused BEFORE the
dial with *wire.CapabilityError naming the token (unwraps to
*storage.ErrUnsupported{Capability: "issues.heartbeat"}); it never falls
back to a re-claim or a metadata stamp.
- The role's request rules are restated before the dial
(validateHeartbeatRequest, pinned to
storeops.ValidateHeartbeatRequest): blank/over-long actor, empty id, each
a *HeartbeatFieldError.
- Problem mapping: already_claimed (which the shared table rebuilds as the
claim's ClaimConflictError) becomes *issueops.LeaseConflictError naming
the holder and wrapping ErrAlreadyClaimed, in the native words ("issue
already claimed by <holder>"); lease_not_held already arrives as
LeaseConflictError (Ephemeral from `reason`); not_found is ErrNotFound;
invalid_argument on `actor` is the role's field error.
- Idempotent: true, the one write this client marks replayable (a repeat
only moves the expiry later; a replay after a reclaim fails the fence).
- Legacy Store.HeartbeatIssue rides the role. Both leave the generated
shell and completeness_test's unsupported allowlist.
- `bd heartbeat` takes Heartbeater() from the resolved store on the direct
routes (dolt, embedded, http) and from the provider's HeartbeaterSource
on the proxied route (exact id resolution in a read unit of work, then
the role); runHeartbeatProxiedServer and heartbeat_proxied_server.go are
deleted. Success output and exit codes are unchanged; refusal text
changes per route (see CHANGELOG).
Tests: heartbeater_test.go (stub server: preflight refusal naming the
token with no POST, request/answer projection, each refusal's typed
mapping including the wisp's reason, the 503 replay, pre-dial validation,
validator parity, the legacy door). served_heartbeater_test.go runs the
18-case contract through env.subject.Heartbeater(), with
HookedHeartbeater wired off a HookFiringStore. TestE2E_HeartbeatOverHTTP:
real bd against an in-process serve: holder ok with revision and
updated_at unchanged and a guarded write with the pre-heartbeat revision
landing; a non-holder refused against an aged lease that stays untouched;
closed, wisp and unclaimed refused, each naming its own state; an older
server's handshake refused naming issues.heartbeat with no write. Corpus
shapes gc-heartbeat, -non-holder, -closed, -wisp pending until
reference_server.json advertises the token. CHANGELOG entry for the whole
track, including the orphaned-lease race fix.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* build(bazel): auto-sync BUILD files
Applied from the bazel-sync-patch artifact of https://github.com/gastownhall/beads/actions/runs/38875641041
(`make bazel-sync`: gazelle, tools/bazel/go_srcs.py, bazel mod tidy).
Only BUILD.bazel, MODULE.bazel and MODULE.bazel.lock are ever pushed; see
scripts/bazel-autofix-push.sh.
* fix(heartbeat): roll back a no-issue refusal; restate refresh vs re-arm
Review fixes for #7600 (adopt-pr apply-fixes, iterations 1-2).
Legacy HeartbeatIssue doors commit a refusal only when it read the issue.
The dolt and embedded HeartbeatIssue callbacks committed every
LeaseRenewalRefusal, including Found=false (the issue read failed). That
refusal deletes nothing, but it can follow a fast-path UPDATE that
already extended an orphan lease row's expiry, so committing it kept the
extension. issueops.LeaseRenewalRefusalCommits now gates the commit on
Found, the rule the Heartbeater role's HeartbeatRefusalCommits applies.
New tests on both legs pin both arms: a no-issue orphan's expiry is
unchanged, and a released issue's orphan is deleted.
Refresh vs re-arm contract docs. Comments, Long help, the OpenAPI spec
and the generated apigen still said every heartbeat writes only the
lease row, makes no Dolt commit and fires no hook. A re-arm is recorded
as a mutation: it remints the revision, records an event and a version
entry, commits once (LeaseRearmVersionCommit) and fires on_update
through the wrapping hook decorator. Restated in domain, uow, issueops,
storage.go (why RoleFiresHooks answers true, so bd serve takes the
heartbeater off a peeled store), cmd/bd heartbeat and serve, httpapi,
httpclient, the spec (apigen regenerated), and the conformance and
contract-test docs.
Minor review findings:
- The 409 already_claimed and lease_not_held details now end "nothing
on the issue was written": the refusal may have deleted and committed
the caller's orphan lease row.
- docs/multi-agent/federation.md and the CHANGELOG entry describe the
spelling-mismatch heartbeat: the row is refreshed in place and keeps
granted_at and granted_node; only a re-arm stamps this node. The
embedded spelling test pins both columns, and the lease.go comments
say "refreshed in place" instead of "re-arms".
- The refusal's orphan delete judges the holder under actorMatches, as
the in-place refresh does (iteration 2). It matched holder = ? on the
actor as sent, so a dead claim's orphan held under another spelling
of the caller (gastown.mayor, heartbeat as gastown__mayor) survived
the refusal until TTL. The refused closure now reads the row's holder
and deletes that stored holder only when actorMatches(holder, actor).
Both TestHeartbeatIssueCommitsARefusalOnlyWhenItReadTheIssue twins
gain a cross-spelling arm (row deleted) and a control: another
identity's row (gastown.dog-3) survives.
Not changed: `bd heartbeat --json` still omits `rearmed`, since adding
it changes a CLI JSON contract (follow-up). The federation.md paragraph
post-dates the v1.2.2 docs pin, so documenting this main-only behaviour
there is a maintainer call under
engdocs/decisions/2026-07-17-docs-release-pin.md section 1.
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(uow): run the scoped re-arm's Dolt commit after the SQL commit
The proxied-server heartbeat commits a re-arm with doltServerTx.CommitScoped,
which ran DOLT_ADD per table and DOLT_COMMIT('-m') INSIDE the open
transaction, before the SQL COMMIT. DOLT_ADD stages whole tables from the
session's transaction root, so that Dolt commit was built from the re-arm's
start snapshot: an issues row another session changed while the re-arm was
open (a write still only in the working set, as in batch mode or before that
writer's own Dolt commit) was staged at its old value, and HEAD disagreed
with the rows every reader sees. This is the LatentLabsSpace/NEXUS#92
ordering the DoltStore funnel (runIssueOperationTxWithMessage) already
avoids, and the review's major finding on this PR.
CommitScoped now commits the SQL transaction first, then stages exactly the
named tables (plus the versioned-history tables) and makes the Dolt commit on
the same pinned connection, the uow twin of doltAddAndCommitPostTx:
- a serialization failure of the SQL COMMIT is still returned, so
RunTxScoped replays the unit of work;
- the Dolt commit runs detached on its own budget and replays only conflicts
that leave nothing behind: serialization failures and Dolt's 1105
"@autocommit transaction rolled back" (new isDoltAutocommitRollbackError,
mirroring the DoltStore classifier of the same name);
- nothing staged, or "nothing to commit", is not an error: a concurrent
writer's Dolt commit already took the row. A "nothing to commit" past the
staged check is logged, as the funnel logs it, so the missing audit line
is explicable;
- any other failure is logged, never returned. The data is committed, and
returning it would make RunTxScoped replay a committed re-arm, which would
then report a refresh. The session is poisoned rather than pooled, since
its state is unknown. uow records no metrics, so that log line is the
drop's only signal; bd.db.post_tx_commit_dropped counts only the funnel's.
Statements go through schema.DrainCall, retiring the local drainCall fork
(review nit).
Tests: five sqlmock tests pin the order (SQL COMMIT before any DOLT_ADD),
the swallow-and-poison path, the 1105 retry, the returned serialization
failure and the empty-commit tolerance; each fails against the previous
CommitScoped. TestIsDoltAutocommitRollbackError carries the DoltStore
classifier's table over to the uow copy, plus the prefix boundary; dropping
the prefix branch, the prefix's period, the 1105 check or the type check
each fails a case. TestHeartbeaterRearmKeepsAConcurrentWrite is the
real-Dolt regression: a change to another issues row made while the
re-arm's transaction is open must be at HEAD after the re-arm's Dolt
commit. Its working-set-only writer fails on the old ordering (dolt
2.1.8); the writer that Dolt-commits its own change passes on both and is
kept as coverage.
Review follow-ups folded in (comments, a file move and a test; the
absorption log line above is the only behaviour change among them):
- the freshRowLock invariant and its row_lock_guard_test.go mirror name the
re-arm as the one deliberate remint without a lifecycle-field change,
load-bearing for the release/close collision;
- httpclient: "a write is never retried" (wire/client.go, stall_retry.go)
and "only a read's answer is yes" (dispatch.go) now allow for the
Idempotent heartbeat, and httpHeartbeater and issueops.HeartbeatResult
document that a replayed heartbeat can report Rearmed false after a
committed re-arm, with the guarded write's revision check as the backstop;
- the proxied route moves back to cmd/bd/heartbeat_proxied_server.go, the
file family cmd/bd/AGENTS.md prescribes;
- the ScopedCommitter and RunTxScoped docs no longer say every other
writer's uncommitted change stays out of the commit: a staged table is
committed whole, so such a change to a named table rides in the re-arm's
commit, as it does in the funnel, and only other tables keep theirs;
- commitStagedTables says its drop is log-only, the absorption is logged,
and the uow classifier gets its table test (see Tests).
Not folded in: the base-owned IssueUseCase.Heartbeat /
IssueSQLRepository.HeartbeatIssue door, dead in production since the
proxied route moved to the Heartbeater role. Its one caller is the
notifying hook-parity test (uow/notifying_test.go), and moving that case
onto the Heartbeater means re-deriving its RenewLease hook semantics, so it
is left for a follow-up.
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 (1M context) <noreply@anthropic.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
886 lines
42 KiB
Go
886 lines
42 KiB
Go
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/wire/problem.go@49d1df2f6)
|
|
// to OSS beads under the MIT license.
|
|
package wire
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
"unicode"
|
|
|
|
"github.com/steveyegge/beads/internal/httpapi/apigen"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
// The refusals with no analog in the local store's vocabulary, because each is
|
|
// a statement about a SERVER rather than about the workspace. Everything else
|
|
// in the code table maps to the canonical issueops sentinel the embedded store
|
|
// would have returned for the same refusal, so a caller classifies a remote
|
|
// refusal with the errors.Is arm it already has.
|
|
var (
|
|
// ErrInvalidCursor is a cursor this server did not issue, cannot decode, or
|
|
// issued under a different internal version. The recovery is to restart
|
|
// paging without it, which is why it is not folded into ErrValidation: a
|
|
// stale cursor is a normal client situation, not a client bug.
|
|
ErrInvalidCursor = errors.New("cursor is not valid for this server; restart paging")
|
|
// ErrUnauthenticated is a missing, malformed or unrecognized credential on
|
|
// a server that was configured with one. It never carries the credential or
|
|
// any hint of which of the three it was — the server refuses to say, and
|
|
// repeating a guess here would undo that.
|
|
ErrUnauthenticated = errors.New("bd serve refused the credential")
|
|
// ErrBusy is retryable contention: the server's transaction retry budget was
|
|
// exhausted, or its in-flight limit was saturated.
|
|
ErrBusy = errors.New("bd serve is busy")
|
|
// ErrDBUnavailable is a retryable failure to reach the served database.
|
|
ErrDBUnavailable = errors.New("bd serve cannot reach its database")
|
|
// ErrServerFault is an unexpected server-side failure. Its detail is a fixed
|
|
// string by design, so ProblemError.RequestID is the only handle on the log
|
|
// line that has the real error.
|
|
ErrServerFault = errors.New("bd serve failed")
|
|
// ErrBadRequest is the 4xx default branch: a code this client does not know,
|
|
// on a status class that says the request was wrong. Failing loud is the
|
|
// documented posture — an unknown 4xx is a client bug, and retrying or
|
|
// degrading past one hides it.
|
|
ErrBadRequest = errors.New("bd serve refused the request")
|
|
|
|
// The journal codes. This client dials no journal operation — httpstore
|
|
// carries no EventsJournal accessor, so nothing here can produce a request
|
|
// that earns one of these — and they are on the code table anyway, because
|
|
// the vocabulary gate is set-equality with the document rather than with
|
|
// what this client happens to reach today. A code the document publishes
|
|
// and this table omitted would take the 4xx default branch and be reported
|
|
// as a client bug on the day the journal accessor lands.
|
|
|
|
// ErrEventsJournalDisabled is the served workspace having its journal OFF.
|
|
// The recovery is entirely the operator's — set `events-journal true` and
|
|
// restart the server — so it is not folded into ErrValidation, which would
|
|
// send a caller looking at its own request.
|
|
ErrEventsJournalDisabled = errors.New("bd serve: the events journal is not enabled on the served workspace")
|
|
// ErrEventsWatchSaturated is the server already holding as many open
|
|
// journal streams as it will. It is NOT ErrBusy despite the shared 503:
|
|
// busy says the database is congested and the same request will work
|
|
// shortly, this says a bounded resource is fully subscribed by connections
|
|
// that may last hours, and the caller has a recovery busy does not offer —
|
|
// the paged read, which holds nothing between requests.
|
|
ErrEventsWatchSaturated = errors.New("bd serve: no journal stream slots are free")
|
|
// ErrPreconditionFailed is a compare-and-set guard that missed on an
|
|
// operation whose contract is that a miss refuses everything. It is the
|
|
// fallback for the shape the server did not name: when `param` says which
|
|
// guard missed, the table answers with the issueops sentinel the embedded
|
|
// store would have returned for the same miss.
|
|
ErrPreconditionFailed = errors.New("bd serve: a precondition on the request did not hold")
|
|
// ErrEventsJournalTruncated is a journal read whose checkpoint has fallen
|
|
// below the retained window. ProblemError carries the window itself
|
|
// (Since/Floor/Head), because the recovery is a decision the consumer makes
|
|
// from those three numbers rather than from this sentence.
|
|
ErrEventsJournalTruncated = errors.New("bd serve: the journal checkpoint is below the retained window")
|
|
|
|
// ErrUnknownItemCode is the PER-ITEM analog of the 4xx default branch above:
|
|
// a BatchCloseItemError.code this client does not recognize. Per-item codes
|
|
// grow additively exactly as Problem.code does — the schema tells clients to
|
|
// default-branch on an unknown one — so an unfamiliar code must not hard-fail
|
|
// the whole batch. It lands as a TYPED per-item outcome instead, so a caller
|
|
// tells "this item was refused for a reason my client is too old to name"
|
|
// from a success rather than reading it as one.
|
|
ErrUnknownItemCode = errors.New("bd serve refused a batch-close item with a code this client does not recognize")
|
|
)
|
|
|
|
// UnknownItemCodeError is the typed carrier for that per-item refusal. It keeps
|
|
// the code verbatim and the server's optional detail so a renderer can show what
|
|
// it could not classify, and unwraps to ErrUnknownItemCode so errors.Is reaches
|
|
// it. Both strings are server-controlled, so the layer that builds one strips
|
|
// their control runes the way mapProblem strips every other wire field.
|
|
type UnknownItemCodeError struct {
|
|
IssueID string
|
|
Code string
|
|
Detail string
|
|
}
|
|
|
|
func (e *UnknownItemCodeError) Error() string {
|
|
if e.Detail != "" {
|
|
return fmt.Sprintf("issue %s: bd serve refused it with an unrecognized batch-close code %q: %s", e.IssueID, e.Code, e.Detail)
|
|
}
|
|
return fmt.Sprintf("issue %s: bd serve refused it with an unrecognized batch-close code %q", e.IssueID, e.Code)
|
|
}
|
|
|
|
func (e *UnknownItemCodeError) Unwrap() error { return ErrUnknownItemCode }
|
|
|
|
// ProblemError is a non-2xx answer from bd serve, decoded from its RFC 9457
|
|
// problem+json body.
|
|
//
|
|
// It carries the whole envelope because the layers above reconstruct typed
|
|
// refusals and user-facing text from it: `code` is the dispatch key, `param`
|
|
// and `reason` turn a 400 back into the flag that produced it, `request_id` is
|
|
// what makes a 5xx actionable, and the extension members are the typed
|
|
// discriminators the server reads inside the refusing transaction.
|
|
//
|
|
// The extension members are POINTERS because presence is load-bearing on three
|
|
// of them: `open_children` separates the two not_closable refusals, `issue_id`
|
|
// separates a hierarchy conflict from a plain scheduling cycle, and
|
|
// `blocker_is_ancestor` is emitted in both polarities and so cannot use absence
|
|
// to mean false.
|
|
type ProblemError struct {
|
|
// Op is the operation id that was dialed, and ServerURL the base URL it was
|
|
// dialed against. Neither comes off the wire; both are what the refusal
|
|
// taxonomy needs to name the server in its text.
|
|
Op string
|
|
ServerURL string
|
|
|
|
Status int
|
|
Code string
|
|
Title string
|
|
Detail string
|
|
Param string
|
|
Reason string
|
|
RequestID string
|
|
|
|
// CredentialSource names the ladder rung whose credential the server refused,
|
|
// set only on a 401 and only when the provider can report it (design D7). It
|
|
// is a provenance label — an env var name, a command's env var, or the
|
|
// credentials file [host:port] — never the credential itself, so it is safe
|
|
// in error text bound for logs and terminals.
|
|
CredentialSource string
|
|
|
|
// RetryAfter is the server's Retry-After header, already bounded (see
|
|
// Options.MaxRetryAfter). Zero when the header was absent, unparseable or
|
|
// in the past.
|
|
RetryAfter time.Duration
|
|
|
|
Assignee *string
|
|
IssueStatus *string
|
|
OpenChildren *int
|
|
ExistingType *string
|
|
RequestedType *string
|
|
IssueID *string
|
|
BlockerID *string
|
|
BlockerIsAncestor *bool
|
|
|
|
// The compare-and-set guard's two sides, with `precondition_failed`. `param`
|
|
// says WHICH guard missed and these say what the request asked for and what
|
|
// the row was found holding, split BY TYPE rather than carried as one
|
|
// polymorphic pair — a member that is "a version or a status or an
|
|
// assignee" is a schema alternation, and this document spells three typed
|
|
// pairs instead.
|
|
//
|
|
// They are pointers for the reason every pointer here is one: PRESENCE is
|
|
// load-bearing on all six. An `expected_*` echoes the request, so its
|
|
// absence means the operation carried no such guard — and 0 and "" are both
|
|
// real guards, so neither zero value can stand in for absence. An `actual_*`
|
|
// is present only where the refusing operation can REPORT what it found: an
|
|
// all-or-nothing operation rolls its transaction back, and a value read
|
|
// after the fact would describe a row the refusal never saw, so absence
|
|
// there means "this server cannot tell you", never "it found zero".
|
|
//
|
|
// THE VERSIONS ARE CARRIED AS THE STRINGS THE WIRE SPELLS THEM IN. Since
|
|
// upstream #6053 every revision token on the surface is a decimal string
|
|
// (types.RevisionToken), never a JSON number, so nothing on this path can
|
|
// round one. They are deliberately NOT parsed back to int64 here: the token
|
|
// is opaque and equality-only, `expected_version` is the ECHO of what the
|
|
// request sent (a caller comparing it to its own guard compares
|
|
// types.RevisionToken(guard) to it), and `actual_version` is a diagnostic —
|
|
// the contract says to compose the next guard from a `revision` a WRITE
|
|
// answered with, never from a refusal. Parsing on the refusal path could
|
|
// only turn a well-formed 409 into a decode failure or drop a member whose
|
|
// presence is load-bearing, and nothing in this package reads them
|
|
// numerically. They are stripped like every other server-controlled string.
|
|
ExpectedVersion *string
|
|
ActualVersion *string
|
|
ExpectedStatus *string
|
|
ActualStatus *string
|
|
ExpectedAssignee *string
|
|
ActualAssignee *string
|
|
|
|
// The batch-item members, on a refusal from an operation whose items are
|
|
// HETEROGENEOUS and may be named — issues:batchApply is the whole
|
|
// population. They are the only place the offender exists: that operation
|
|
// is all or nothing, so a refusal carries no per-item result array for a
|
|
// client to find it in, and the server reads these off the role's own typed
|
|
// *issueops.ItemError inside the transaction that refused.
|
|
//
|
|
// PRESENCE IS LOAD-BEARING ON ALL OF THEM, which is why the index is a
|
|
// pointer and not an int: 0 is the FIRST ITEM and a real answer, so a bare
|
|
// int could not tell it from a refusal that named no item at all. Key and
|
|
// IssueID are absent for real states rather than gaps — not every item
|
|
// carries a key, and a create whose id was never minted has none to report.
|
|
//
|
|
// ItemIssueID is deliberately NOT ProblemError.IssueID, and the divergence
|
|
// is the server's rather than a spelling choice here: IssueID's PRESENCE
|
|
// discriminates the dependency_cycle hierarchy refusal from the plain
|
|
// scheduling one, so a batch reusing it would fire that discriminator on
|
|
// refusals it says nothing about.
|
|
ItemIndex *int
|
|
ItemKind *string
|
|
ItemKey *string
|
|
ItemIssueID *string
|
|
// DeclaredLater tells the two unresolvable-key diagnoses apart: true is an
|
|
// ORDERING mistake — the key IS declared, by a later item, and a key
|
|
// reaches backward only — and false is a key nothing in the request
|
|
// declares, which is a typo or a missing item. It is emitted in BOTH
|
|
// polarities, so it is a pointer for the reason BlockerIsAncestor is one:
|
|
// absence has to mean "this refusal was not about a key", never false.
|
|
DeclaredLater *bool
|
|
|
|
// The journal-truncation window, with `events_journal_truncated`: the
|
|
// checkpoint the window begins after, the lowest seq still retained, and the
|
|
// highest seq ever assigned.
|
|
//
|
|
// They are carried rather than folded into the sentinel because that
|
|
// sentinel is storage.EventsJournalTruncatedError, and this package
|
|
// deliberately imports no storage — the whole point of respelling the
|
|
// operation ids here is that a process talking to a bd serve does not link
|
|
// the engine. A consumer with a journal accessor rebuilds the typed error
|
|
// from these three; without them the recovery (resume from floor-1 and
|
|
// accept the gap, or re-baseline) would have to be parsed out of prose.
|
|
Since *int64
|
|
Floor *int64
|
|
Head *int64
|
|
|
|
// Err is the canonical sentinel this code maps to. It is what Unwrap
|
|
// returns, so errors.Is and errors.As reach it.
|
|
Err error
|
|
}
|
|
|
|
func (e *ProblemError) Error() string {
|
|
var b strings.Builder
|
|
fmt.Fprintf(&b, "%s: bd serve at %s answered %d", e.Op, e.ServerURL, e.Status)
|
|
if e.Code != "" {
|
|
fmt.Fprintf(&b, " %s", e.Code)
|
|
}
|
|
if e.Detail != "" {
|
|
fmt.Fprintf(&b, ": %s", e.Detail)
|
|
}
|
|
// The 5xx detail is a fixed string per code and says nothing about the
|
|
// underlying failure, so the correlation id is the client's only handle on
|
|
// the one server log line that has it.
|
|
if e.Status >= 500 && e.RequestID != "" {
|
|
fmt.Fprintf(&b, " (request_id %s)", e.RequestID)
|
|
}
|
|
// Naming the rung the refused credential came from is what turns "the server
|
|
// said 401" into something the operator can act on: it says WHICH source to
|
|
// rotate or fix (design D7). The server never says which of missing,
|
|
// malformed or unrecognized it was, and this does not guess — it reports only
|
|
// the client-side provenance of the credential it presented.
|
|
if e.Status == http.StatusUnauthorized && e.CredentialSource != "" {
|
|
fmt.Fprintf(&b, " (credential from %s)", e.CredentialSource)
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
func (e *ProblemError) Unwrap() error { return e.Err }
|
|
|
|
// Retryable reports whether the server said to come back. Only the 503 class
|
|
// says so: an unknown 4xx is a client bug and every other 5xx is a fault the
|
|
// same request will earn again.
|
|
func (e *ProblemError) Retryable() bool {
|
|
return e.Status == http.StatusServiceUnavailable ||
|
|
errors.Is(e.Err, ErrBusy) || errors.Is(e.Err, ErrDBUnavailable)
|
|
}
|
|
|
|
// ReasonProjectMismatch is the Problem `reason` the server sets on a refusal of
|
|
// a Bd-Project-Id stamp for the wrong workspace, spelled exactly as the server's
|
|
// httpapi.ReasonProjectMismatch (held to it by
|
|
// TestProjectMismatchReasonMatchesTheServerConstant). It is the discriminator
|
|
// mapProblem reads to build the typed *ProjectMismatchError, ahead of the code
|
|
// table: the code is the generic invalid_argument, so reason is the only thing
|
|
// that tells this wrong-server refusal from a malformed-argument one.
|
|
const ReasonProjectMismatch = "project_mismatch"
|
|
|
|
// ReasonWireRevisionUnsupported is the Problem `reason` the server sets when
|
|
// this client's declared Bd-Wire-Revision header named a revision below the
|
|
// server's own min_client_wire_revision, spelled exactly as the server's
|
|
// httpapi.ReasonWireRevisionUnsupported (held to it by
|
|
// TestTheProjectIdentityVocabularyMatchesTheServer). Like ReasonProjectMismatch
|
|
// it rides the generic invalid_argument code, so reason is the only thing that
|
|
// tells this refusal apart from an ordinary malformed argument.
|
|
const ReasonWireRevisionUnsupported = "wire_revision_unsupported"
|
|
|
|
// ReasonEphemeral is the Problem `reason` that qualifies a lease_not_held: the
|
|
// id names a wisp, which is never leased. Spelled exactly as the server's
|
|
// httpapi.ReasonEphemeral (held to it by the vocabulary test).
|
|
const ReasonEphemeral = "ephemeral"
|
|
|
|
// ErrWireRevisionUnsupported reports that bd serve refused this client's
|
|
// declared Bd-Wire-Revision header as older than the revision it now
|
|
// requires. See WireRevisionUnsupportedError.
|
|
var ErrWireRevisionUnsupported = errors.New("bd serve requires a newer client wire revision than this client declared")
|
|
|
|
// WireRevisionUnsupportedError is the per-request mirror of the handshake's
|
|
// own gate (wire.WireRevisionSkewError, handshake.go): the server has read
|
|
// this client's declared Bd-Wire-Revision header (wire.ClientWireRevision,
|
|
// stamped on every request by Client.stampRequest) and refused it as below
|
|
// the floor it enforces now. Unlike WireRevisionSkewError — raised locally,
|
|
// from a 200 ContextResponse, when THIS client decides the SERVER's wire
|
|
// shape is one it cannot speak — this one is the SERVER's own refusal, and it
|
|
// can arrive on any request, including the context fetch the handshake
|
|
// itself makes (ContextResponse.MinClientWireRevision's doc: "raised ... on
|
|
// GET /v0/beads/context too"), in which case it surfaces through
|
|
// Client.Handshake exactly the way any other *ProblemError from GetContext
|
|
// does — no separate handling is needed there.
|
|
type WireRevisionUnsupportedError struct {
|
|
ServerURL string
|
|
BdVersion string
|
|
// ClientWireRevision is this build's own declared revision, which is what
|
|
// was refused.
|
|
ClientWireRevision int
|
|
// MinClientWireRevision is the server's own floor, from the refusal's
|
|
// min_wire_revision extension member.
|
|
MinClientWireRevision int
|
|
// ServerWireRevision is the server's own current wire_revision, from the
|
|
// refusal's wire_revision extension member.
|
|
ServerWireRevision int
|
|
}
|
|
|
|
func (e *WireRevisionUnsupportedError) Error() string {
|
|
return fmt.Sprintf("bd serve at %s (bd_version %s) requires a client wire revision of at least %d; this client declared %d",
|
|
e.ServerURL, e.BdVersion, e.MinClientWireRevision, e.ClientWireRevision)
|
|
}
|
|
|
|
func (e *WireRevisionUnsupportedError) Unwrap() error { return ErrWireRevisionUnsupported }
|
|
|
|
// target names the ids the wire's conflict members leave out. The server does
|
|
// not echo the issue a claim refused or the edge a dependency_exists collided
|
|
// with — the request already said — so the caller supplies them and the
|
|
// reconstructed sentinel comes out whole.
|
|
type target struct {
|
|
op string
|
|
serverURL string
|
|
issueID string
|
|
dependsOnID string
|
|
// actor is the request's acting identity (Request.Actor), which the
|
|
// not_assignee refusal names and the wire does not repeat.
|
|
actor string
|
|
// expectID is the workspace's own pinned project id (Client.expectID), which
|
|
// the wire never carries — it is a client-side fact. A project_mismatch
|
|
// refusal names the server's own id in server_project_id; pairing it with this
|
|
// expected id is what lets the typed *ProjectMismatchError say BOTH sides of
|
|
// the disagreement without the client parsing the refusal's prose.
|
|
expectID string
|
|
}
|
|
|
|
// mapProblem decodes an RFC 9457 body and maps it onto the canonical sentinel
|
|
// for its code.
|
|
//
|
|
// `code` is the ONLY dispatch key, per the document: a code carries one frozen
|
|
// status, so reading the status instead would be a second, weaker copy of the
|
|
// same table. The status is consulted for exactly one thing — the default
|
|
// branch for a code this client has never heard of, which is how the vocabulary
|
|
// stays additive.
|
|
func mapProblem(t target, status int, header http.Header, body []byte, maxRetryAfter time.Duration) *ProblemError {
|
|
var p apigen.Problem
|
|
// A non-2xx that is not problem+json at all is a real case: a proxy, a load
|
|
// balancer or a stray server on the port answers with HTML. It falls through
|
|
// to the status-class default branch with an empty code, which is exactly
|
|
// what an unrecognized code does.
|
|
_ = json.Unmarshal(body, &p)
|
|
|
|
// Every string that comes off the wire here is server-controlled and ends up
|
|
// in an error rendered to a terminal or a log line — often through a %v sink
|
|
// that never touches the CLI's output-boundary strip (bd close/show/reopen/
|
|
// update write each per-id failure straight to os.Stderr). So the control
|
|
// runes are removed HERE, the moment the bytes become a typed error, and both
|
|
// the direct fields AND the extension members the typed conflicts are
|
|
// reconstructed from below (sentinelFor) are cleaned — an issue id echoed by a
|
|
// dependency-cycle conflict is as server-controlled as the detail string. The
|
|
// pointer members keep their presence, which is load-bearing discrimination on
|
|
// three of them. Tab and newline are stripped too (unlike the display-layer
|
|
// strip): a problem field is a single value with no legitimate framing.
|
|
e := &ProblemError{
|
|
Op: t.op,
|
|
ServerURL: t.serverURL,
|
|
Status: status,
|
|
Code: stripControlRunes(p.Code),
|
|
Title: stripControlRunes(p.Title),
|
|
Detail: stripControlRunes(deref(p.Detail)),
|
|
Param: stripControlRunes(deref(p.Param)),
|
|
Reason: stripControlRunes(deref(p.Reason)),
|
|
RequestID: stripControlRunes(p.RequestId),
|
|
RetryAfter: retryAfter(header, maxRetryAfter),
|
|
Assignee: stripControlRunesPtr(p.Assignee),
|
|
IssueStatus: stripControlRunesPtr(p.IssueStatus),
|
|
OpenChildren: p.OpenChildren,
|
|
ExistingType: stripControlRunesPtr(p.ExistingType),
|
|
RequestedType: stripControlRunesPtr(p.RequestedType),
|
|
IssueID: stripControlRunesPtr(p.IssueId),
|
|
BlockerID: stripControlRunesPtr(p.BlockerId),
|
|
BlockerIsAncestor: p.BlockerIsAncestor,
|
|
Since: p.Since,
|
|
Floor: p.Floor,
|
|
Head: p.Head,
|
|
// The guard pair. All six are strings on the wire — the two versions
|
|
// are decimal revision tokens (types.RevisionToken) and are carried as
|
|
// the strings the server spelled, see the field comment — and all six
|
|
// are stripped like every other server-controlled field, keeping their
|
|
// PRESENCE, which is the state that discriminates.
|
|
ExpectedVersion: stripControlRunesPtr(p.ExpectedVersion),
|
|
ActualVersion: stripControlRunesPtr(p.ActualVersion),
|
|
ExpectedStatus: stripControlRunesPtr(p.ExpectedStatus),
|
|
ActualStatus: stripControlRunesPtr(p.ActualStatus),
|
|
ExpectedAssignee: stripControlRunesPtr(p.ExpectedAssignee),
|
|
ActualAssignee: stripControlRunesPtr(p.ActualAssignee),
|
|
// The batch-item members. The three strings are stripped like every
|
|
// other server-controlled field and keep their presence; the index and
|
|
// the ordering discriminator travel as the generated pointers, which is
|
|
// what keeps a zero index and a false polarity apart from absence.
|
|
ItemIndex: p.ItemIndex,
|
|
ItemKind: stripControlRunesPtr(p.ItemKind),
|
|
ItemKey: stripControlRunesPtr(p.ItemKey),
|
|
ItemIssueID: stripControlRunesPtr(p.ItemIssueId),
|
|
DeclaredLater: p.DeclaredLater,
|
|
}
|
|
legacyRevisionFields(body, e)
|
|
|
|
// The wrong-server arm, discriminated on REASON and taken BEFORE the code
|
|
// table. A project_mismatch is spelled invalid_argument on the wire, so the
|
|
// code table would map it to ErrValidation and lose the whole signal; the
|
|
// reason is what tells it apart. It is the one refusal that carries
|
|
// server_project_id — the id the server actually serves — which is stripped
|
|
// here at the decode boundary like every other server-controlled field and is
|
|
// deliberately NOT a generic ProblemError member: it exists only to build this
|
|
// typed error, paired with the workspace's own expected id, and unwraps
|
|
// ErrProjectMismatch so cmd/bd renders one recovery block for both this
|
|
// per-request path and the handshake identity gate. Database and RepoRoot are
|
|
// left empty: this refusal discloses only the server's id, not its location.
|
|
if e.Reason == ReasonProjectMismatch {
|
|
e.Err = &ProjectMismatchError{
|
|
ServerURL: t.serverURL,
|
|
Expected: t.expectID,
|
|
Got: stripControlRunes(deref(p.ServerProjectId)),
|
|
}
|
|
return e
|
|
}
|
|
|
|
// The other document-level arm, discriminated the same way and for the
|
|
// same reason: wire_revision_unsupported rides the generic
|
|
// invalid_argument code too, so reason is what tells it apart. The three
|
|
// extension members it alone carries are read straight off the problem —
|
|
// stripped like every other server-controlled field — rather than folded
|
|
// into the generic ProblemError, because this refusal is a statement about
|
|
// the SERVER's wire shape, not about the request's arguments.
|
|
if e.Reason == ReasonWireRevisionUnsupported {
|
|
e.Err = &WireRevisionUnsupportedError{
|
|
ServerURL: t.serverURL,
|
|
BdVersion: stripControlRunes(deref(p.BdVersion)),
|
|
ClientWireRevision: ClientWireRevision,
|
|
MinClientWireRevision: deref(p.MinWireRevision),
|
|
ServerWireRevision: deref(p.WireRevision),
|
|
}
|
|
return e
|
|
}
|
|
|
|
e.Err = sentinelFor(e, t)
|
|
return e
|
|
}
|
|
|
|
// decodeRevisionToken reads a revision-bearing problem member that may be
|
|
// encoded either as the decimal string every server since upstream #6053
|
|
// uses (types.RevisionToken) or as the bare JSON integer a server old enough
|
|
// to omit ContextResponse.wire_revision entirely still sends (see
|
|
// ClientMinWireRevision's doc: a decoded 0 means the server omitted the
|
|
// member, and 0 is exactly the pre-#6053 integer-token generation). Both
|
|
// shapes name the same opaque token — this client never parses either one
|
|
// back to int64 (ProblemError.ExpectedVersion's doc) — so tolerating the
|
|
// older shape here is only about surviving the decode, never about deriving a
|
|
// number from it.
|
|
func decodeRevisionToken(raw json.RawMessage) (string, bool) {
|
|
if len(raw) == 0 || string(raw) == "null" {
|
|
return "", false
|
|
}
|
|
var s string
|
|
if err := json.Unmarshal(raw, &s); err == nil {
|
|
return s, true
|
|
}
|
|
var n json.Number
|
|
if err := json.Unmarshal(raw, &n); err == nil {
|
|
return n.String(), true
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
// revisionNeedsFallback reports whether a *string revision field still needs
|
|
// legacyRevisionFields' integer-tolerant recovery. A genuinely absent member
|
|
// decodes to nil, as expected — but encoding/json's indirect() allocates a
|
|
// pointer to the zero value ("") for a *string field BEFORE it discovers the
|
|
// JSON value's type doesn't match, when the member IS present with the wrong
|
|
// shape (a bare integer). That pre-allocation means a type-mismatched field
|
|
// comes out of the primary json.Unmarshal(body, &p) as a non-nil pointer to
|
|
// "", not nil — so checking only for nil here would never recover exactly the
|
|
// one case this fallback exists for. No legitimate server response uses a
|
|
// literal empty-string revision token (ProblemError.ExpectedVersion's doc:
|
|
// both are opaque, server-defined, non-numeric tokens an operation always
|
|
// names when it fires at all), so treating "" the same as nil costs nothing.
|
|
func revisionNeedsFallback(p *string) bool {
|
|
return p == nil || *p == ""
|
|
}
|
|
|
|
// legacyRevisionFields backfills expected_version/actual_version when the
|
|
// primary decode above left them needing fallback (see revisionNeedsFallback).
|
|
// That happens exactly when a pre-#6053 server sent one as a bare JSON
|
|
// integer rather than the decimal string every server since has used:
|
|
// json.Unmarshal(body, &p) already tolerates the mismatch (a bad field does
|
|
// not abort decoding the rest, and mapProblem deliberately discards that
|
|
// error), so the only member actually lost is the one with the wrong shape —
|
|
// and that is exactly what this recovers, from the same bytes, by parsing the
|
|
// two revision keys alone and accepting either shape.
|
|
func legacyRevisionFields(body []byte, e *ProblemError) {
|
|
if !revisionNeedsFallback(e.ExpectedVersion) && !revisionNeedsFallback(e.ActualVersion) {
|
|
return
|
|
}
|
|
var raw struct {
|
|
ExpectedVersion json.RawMessage `json:"expected_version"`
|
|
ActualVersion json.RawMessage `json:"actual_version"`
|
|
}
|
|
if json.Unmarshal(body, &raw) != nil {
|
|
return
|
|
}
|
|
if revisionNeedsFallback(e.ExpectedVersion) {
|
|
if v, ok := decodeRevisionToken(raw.ExpectedVersion); ok {
|
|
v = stripControlRunes(v)
|
|
e.ExpectedVersion = &v
|
|
}
|
|
}
|
|
if revisionNeedsFallback(e.ActualVersion) {
|
|
if v, ok := decodeRevisionToken(raw.ActualVersion); ok {
|
|
v = stripControlRunes(v)
|
|
e.ActualVersion = &v
|
|
}
|
|
}
|
|
}
|
|
|
|
// codeSentinel is the whole problem-code vocabulary this client knows, and the
|
|
// canonical error each code becomes.
|
|
//
|
|
// It is a table rather than a switch so the vocabulary is ENUMERABLE:
|
|
// TestTheCodeTableIsSetEqualWithTheDocumentedVocabulary walks it against the
|
|
// `x-bd-codes` rows of the shipped OpenAPI document, in both directions, which
|
|
// a switch statement could not be held to.
|
|
var codeSentinel = map[string]func(*ProblemError, target) error{
|
|
"invalid_argument": func(*ProblemError, target) error { return issueops.ErrValidation },
|
|
"invalid_cursor": func(*ProblemError, target) error { return ErrInvalidCursor },
|
|
"unauthenticated": func(*ProblemError, target) error { return ErrUnauthenticated },
|
|
"not_found": func(*ProblemError, target) error { return issueops.ErrNotFound },
|
|
"already_exists": func(*ProblemError, target) error { return issueops.ErrAlreadyExists },
|
|
"busy": func(*ProblemError, target) error { return ErrBusy },
|
|
"db_unavailable": func(*ProblemError, target) error { return ErrDBUnavailable },
|
|
"internal": func(*ProblemError, target) error { return ErrServerFault },
|
|
|
|
// The journal codes, on the table for the reason stated beside their
|
|
// sentinels: set-equality with the document, not with what this client
|
|
// reaches today.
|
|
"events_journal_disabled": func(*ProblemError, target) error { return ErrEventsJournalDisabled },
|
|
"events_journal_truncated": func(*ProblemError, target) error { return ErrEventsJournalTruncated },
|
|
"events_watch_saturated": func(*ProblemError, target) error { return ErrEventsWatchSaturated },
|
|
|
|
// `param` names WHICH guard missed, in the same spelling a 400 on the same
|
|
// operation would use, so the client answers with the issueops sentinel the
|
|
// embedded store returns for that miss and a caller classifies both
|
|
// backends with one errors.Is arm. An unrecognized (or absent) param takes
|
|
// the generic sentinel rather than guessing one of the three.
|
|
//
|
|
// The MEMBER is read off the end of the param rather than compared whole,
|
|
// because a batch operation qualifies it by the item that carried the
|
|
// guard: `items[1].update.expected_version` is the same member as
|
|
// `expected_version` and means the same miss. A whole-string comparison
|
|
// answered the generic sentinel for every guarded item in a plan, which is
|
|
// a caller told "a precondition failed" where a local backend tells it
|
|
// WHICH — see paramMember.
|
|
"precondition_failed": func(e *ProblemError, _ target) error {
|
|
switch paramMember(e.Param) {
|
|
case "expected_version":
|
|
return issueops.ErrVersionMismatch
|
|
case "expected_status":
|
|
return issueops.ErrStatusMismatch
|
|
case "expected_assignee":
|
|
return issueops.ErrAssigneeMismatch
|
|
default:
|
|
return ErrPreconditionFailed
|
|
}
|
|
},
|
|
|
|
"already_claimed": func(e *ProblemError, t target) error {
|
|
return claimConflict(e, t, issueops.ErrAlreadyClaimed)
|
|
},
|
|
"not_claimable": func(e *ProblemError, t target) error {
|
|
return claimConflict(e, t, issueops.ErrNotClaimable)
|
|
},
|
|
|
|
// Member PRESENCE is the discriminator the server documents: the
|
|
// open-children refusal carries the count, the live-blocker one carries
|
|
// nothing. Reading `detail` to tell them apart is exactly what the extension
|
|
// member exists to prevent.
|
|
"not_closable": func(e *ProblemError, t target) error {
|
|
if e.OpenChildren != nil {
|
|
return &issueops.CloseOpenChildrenError{IssueID: refusedIssueID(e, t), OpenChildren: *e.OpenChildren}
|
|
}
|
|
return issueops.ErrCloseBlocked
|
|
},
|
|
|
|
// not_releasable is the RELEASE's refusal, and it is REACHED: httpReleaser
|
|
// dials issues:release (releaser.go, client wave ga-f352s) and nine of the
|
|
// eleven Releaser contracts run through this mapping on the served tier.
|
|
//
|
|
// It was on this table BEFORE it was reachable, for the journal codes'
|
|
// reason — set-equality with the document rather than with what this client
|
|
// happens to dial — and that is worth keeping now that the wait is over: a
|
|
// code the document publishes and this table omitted would take the 4xx
|
|
// default branch and be reported as a client bug on the day an accessor
|
|
// started earning it.
|
|
//
|
|
// The role splits the refusal in two where the wire does not: ErrNotClaimed
|
|
// for a row holding no claim, ErrNotReleasable for a status that will not
|
|
// accept one. One code covers both by the server's own deliberate choice
|
|
// (see httpapi's CodeNotReleasable), and it carries no member that tells
|
|
// them apart, so this maps to the STATUS sentinel — the wider of the two,
|
|
// and the one whose message does not assert a fact the wire never sent.
|
|
"not_releasable": func(*ProblemError, target) error { return issueops.ErrNotReleasable },
|
|
|
|
// lease_not_held is the HEARTBEAT's refusal: the actor holds no live claim
|
|
// (open, closed, released, reclaimed, moved off in_progress, or a wisp).
|
|
// httpclient's Heartbeater reaches it (heartbeater.go). The typed error is
|
|
// rebuilt whole from `issue_status` and `reason: ephemeral` (a wisp), and
|
|
// it wraps ErrLeaseNotHeld, which also matches ErrNotClaimable, in the
|
|
// native heartbeat's own words ("<id> status <status>", "<id> is
|
|
// ephemeral").
|
|
"lease_not_held": func(e *ProblemError, t target) error {
|
|
id := refusedIssueID(e, t)
|
|
status := deref(e.IssueStatus)
|
|
conflict := &issueops.LeaseConflictError{
|
|
IssueID: id,
|
|
Status: issueops.Status(status),
|
|
Ephemeral: e.Reason == ReasonEphemeral,
|
|
Err: issueops.ErrLeaseNotHeld,
|
|
}
|
|
switch {
|
|
case conflict.Ephemeral:
|
|
conflict.Err = fmt.Errorf("%w: %s is ephemeral", issueops.ErrLeaseNotHeld, id)
|
|
case status != "":
|
|
conflict.Err = fmt.Errorf("%w: %s status %s", issueops.ErrLeaseNotHeld, id, status)
|
|
}
|
|
return conflict
|
|
},
|
|
|
|
// [Added: OSS publishes notes_overwrite_refused (internal/httpapi/problem.go
|
|
// CodeNotesOverwrite, status 409) for an update whose Patch.Notes would
|
|
// replace existing notes without an explicit overwrite flag. This code had
|
|
// no entry at all, so a server sending it fell through to the 4xx default
|
|
// and reported as an undifferentiated client bug instead of the typed
|
|
// sentinel callers already switch on locally.]
|
|
"notes_overwrite_refused": func(*ProblemError, target) error { return issueops.ErrNotesOverwrite },
|
|
|
|
// The close guards (the first, template read-only, is every update's guard
|
|
// too), rebuilt whole so a caller reads the same typed error — and the same
|
|
// message — the embedded store returns. The row comes from the request or,
|
|
// on a batch, from `item_issue_id`; the holder from `assignee`; the closing
|
|
// actor from the request, which the wire does not repeat.
|
|
"template_read_only": func(e *ProblemError, t target) error {
|
|
return &issueops.TemplateReadOnlyError{IssueID: refusedIssueID(e, t)}
|
|
},
|
|
"issue_pinned": func(e *ProblemError, t target) error {
|
|
return &issueops.PinnedError{IssueID: refusedIssueID(e, t)}
|
|
},
|
|
"not_assignee": func(e *ProblemError, t target) error {
|
|
return &issueops.CloseNotAssigneeError{IssueID: refusedIssueID(e, t), Assignee: deref(e.Assignee), Actor: t.actor}
|
|
},
|
|
|
|
// The same rule again: `issue_id` present means the edge named the issue's
|
|
// own ancestor or descendant, absent means a plain scheduling cycle. The
|
|
// three hierarchy members travel together and rebuild the typed error whole
|
|
// — including BlockerIsAncestor's false polarity, which is why the wire
|
|
// sends the boolean rather than omitting it.
|
|
"dependency_cycle": func(e *ProblemError, _ target) error {
|
|
if e.IssueID != nil {
|
|
return &issueops.DependencyHierarchyConflictError{
|
|
IssueID: *e.IssueID,
|
|
BlockerID: deref(e.BlockerID),
|
|
BlockerIsAncestor: deref(e.BlockerIsAncestor),
|
|
}
|
|
}
|
|
return issueops.ErrDependencyCycle
|
|
},
|
|
|
|
// The endpoints are not on the wire — the request already said them — so
|
|
// they come from the caller and the typed error comes out whole. A batch add
|
|
// that refused on one of many edges leaves them empty, because the wire does
|
|
// not say WHICH edge collided.
|
|
"dependency_exists": func(e *ProblemError, t target) error {
|
|
return &issueops.DependencyTypeConflictError{
|
|
IssueID: t.issueID,
|
|
DependsOnID: t.dependsOnID,
|
|
ExistingType: deref(e.ExistingType),
|
|
RequestedType: deref(e.RequestedType),
|
|
}
|
|
},
|
|
}
|
|
|
|
// Codes lists the problem codes this client maps, sorted. Anything outside it
|
|
// takes the status-class default branch.
|
|
func Codes() []string {
|
|
out := make([]string, 0, len(codeSentinel))
|
|
for code := range codeSentinel {
|
|
out = append(out, code)
|
|
}
|
|
slices.Sort(out)
|
|
return out
|
|
}
|
|
|
|
func sentinelFor(e *ProblemError, t target) error {
|
|
if row, ok := codeSentinel[e.Code]; ok {
|
|
return row(e, t)
|
|
}
|
|
|
|
// The default branch. Adding a code is not a breaking change, so a client
|
|
// that hard-failed on an unknown one would break on every server newer than
|
|
// itself; falling back to the status class is what makes the vocabulary
|
|
// additive.
|
|
switch {
|
|
case e.Status == http.StatusUnauthorized:
|
|
// A 401 is authentication whether or not the answer carried a problem
|
|
// document, and it must be classified BEFORE the 4xx default. bd serve's
|
|
// own 401 arrives with a code and never reaches here; what does is a 401
|
|
// from something in FRONT of it — a gateway or a proxy edge rejecting an
|
|
// expired credential before the request ever reaches bd — which answers
|
|
// with its own html or nothing at all. Falling through to ErrBadRequest
|
|
// told the caller its REQUEST was malformed, which sends an operator
|
|
// looking at flags for a credential to rotate.
|
|
return ErrUnauthenticated
|
|
case e.Status == http.StatusServiceUnavailable:
|
|
return ErrBusy
|
|
case e.Status >= 500:
|
|
return ErrServerFault
|
|
case e.Status >= 400:
|
|
return ErrBadRequest
|
|
default:
|
|
// A 1xx or 3xx reaching here is not a problem document at all. 3xx is
|
|
// refused before this point (redirects are not followed), so this is the
|
|
// unreachable arm — it fails as a server fault rather than as success.
|
|
return ErrServerFault
|
|
}
|
|
}
|
|
|
|
// claimConflict rebuilds *issueops.ClaimConflictError from the two extension
|
|
// members the refusing transaction read. The wrapped sentinel is what
|
|
// errors.Is matches, so a caller that only wants "someone else has it" needs no
|
|
// errors.As at all.
|
|
func claimConflict(e *ProblemError, t target, sentinel error) error {
|
|
return &issueops.ClaimConflictError{
|
|
IssueID: refusedIssueID(e, t),
|
|
Assignee: deref(e.Assignee),
|
|
Status: issueops.Status(deref(e.IssueStatus)),
|
|
Err: sentinel,
|
|
}
|
|
}
|
|
|
|
// refusedIssueID names the row a reconstructed conflict is about.
|
|
//
|
|
// The REQUEST is the first source and stays the first source: the conflict
|
|
// members the server leaves out are the ones the request already said, which is
|
|
// what target exists for. But a BATCH names as many rows as it has items, so
|
|
// there is no single request id to supply — and on that operation the server
|
|
// publishes the one it acted on as `item_issue_id`, read inside the refusing
|
|
// transaction. Without this fallback every conflict rebuilt from a plan named
|
|
// the empty string, which reads as "the server did not say" when the server
|
|
// said it plainly.
|
|
func refusedIssueID(e *ProblemError, t target) string {
|
|
if t.issueID != "" {
|
|
return t.issueID
|
|
}
|
|
return deref(e.ItemIssueID)
|
|
}
|
|
|
|
// paramMember reads the offending MEMBER off a problem's `param`.
|
|
//
|
|
// A single-resource operation spells it bare (`expected_version`); a batch
|
|
// qualifies it by the item that carried it (`items[1].update.expected_version`)
|
|
// so a client can find the offender in a request it composed. The member is the
|
|
// last dotted segment either way, and reading it is what lets one code table
|
|
// serve both spellings.
|
|
func paramMember(param string) string {
|
|
if i := strings.LastIndex(param, "."); i >= 0 {
|
|
return param[i+1:]
|
|
}
|
|
return param
|
|
}
|
|
|
|
// retryAfter reads the header RFC 9110 defines in two spellings and bounds it.
|
|
//
|
|
// The bound is not politeness: the header is server-controlled input, and an
|
|
// unbounded honor is a server (or anything that can answer as one) parking the
|
|
// caller's process for as long as it likes. A value past the bound is clamped
|
|
// rather than dropped, because the server still meant "not immediately".
|
|
//
|
|
// Honoring it means bounding it and handing it to the caller — this layer never
|
|
// sleeps and never resends. Half of this surface is non-idempotent custom-method
|
|
// POSTs (claim, close, sweep, delete, the dependency writes), and a transport
|
|
// that slept and resent one of those on a 503 would double-apply a write whose
|
|
// first attempt may well have committed before the server ran out of slots.
|
|
// Which 503s are safe to come back to is the dispatch layer's question, and it
|
|
// is the layer that knows the answer.
|
|
func retryAfter(header http.Header, max time.Duration) time.Duration {
|
|
raw := strings.TrimSpace(header.Get("Retry-After"))
|
|
if raw == "" {
|
|
return 0
|
|
}
|
|
var d time.Duration
|
|
if secs, err := strconv.Atoi(raw); err == nil {
|
|
d = time.Duration(secs) * time.Second
|
|
} else if at, err := http.ParseTime(raw); err == nil {
|
|
d = time.Until(at)
|
|
} else {
|
|
return 0
|
|
}
|
|
if d < 0 {
|
|
return 0
|
|
}
|
|
if max > 0 && d > max {
|
|
return max
|
|
}
|
|
return d
|
|
}
|
|
|
|
func deref[T any](p *T) T {
|
|
if p == nil {
|
|
var zero T
|
|
return zero
|
|
}
|
|
return *p
|
|
}
|
|
|
|
// stripControlRunes removes every control rune from a server-controlled problem
|
|
// field: category Cc — the C0 block, DEL and the C1 block, where ESC 0x1B and CSI
|
|
// 0x9B live — plus the U+2028/U+2029 line and paragraph separators. It mirrors the
|
|
// server's own actor rule (httpapi's isControlChar) and, unlike the CLI's
|
|
// display-layer strip, keeps nothing back: a problem field is a single value, so
|
|
// tab and newline in one are as much an injection as an escape introducer. This
|
|
// is the source-of-truth layer — it makes a decoded *ProblemError safe in EVERY
|
|
// field before it reaches any of the many stderr sinks that render it via %v.
|
|
func stripControlRunes(s string) string {
|
|
if !strings.ContainsFunc(s, isControlRune) {
|
|
return s
|
|
}
|
|
return strings.Map(func(r rune) rune {
|
|
if isControlRune(r) {
|
|
return -1
|
|
}
|
|
return r
|
|
}, s)
|
|
}
|
|
|
|
// stripControlRunesPtr strips a pointer member in place-safe fashion, preserving
|
|
// nil. Presence is load-bearing on three of the extension members (an explicit
|
|
// value versus an absent one discriminates two refusals), so a cleaned value is
|
|
// returned through a fresh pointer and an absent one stays absent.
|
|
func stripControlRunesPtr(p *string) *string {
|
|
if p == nil {
|
|
return nil
|
|
}
|
|
s := stripControlRunes(*p)
|
|
return &s
|
|
}
|
|
|
|
func isControlRune(r rune) bool {
|
|
return unicode.IsControl(r) || r == '\u2028' || r == '\u2029'
|
|
}
|