THE TWO ROUTES DISAGREED ABOUT WHAT --force MEANS on a destructive command.
On a local database `--force` deletes the named beads and orphans their
dependents; on a team server it deleted the whole dependent subtree, `--cascade`
was REFUSED outright ("not supported in proxied-server mode (delete always
cascades)") and Cascade was hardcoded true at both call sites. So there was no
way to delete one bead on a team server without taking everything under it, and
asking for the safer behaviour was an error.
Q1 ANSWERED IN THE ROLE. issueops.Deleter has one method, reached through
store.Deleter() and the provider's own accessor, and the three modes are request
fields: no flags refuses over a dependent the request did not name, Force
orphans it, Cascade deletes the closure. The guard is workapi's and the body's,
below every front door, for the reason Sweeper's require-a-filter gate is: a
second front door that inherited the capability without the guard would orphan a
workspace's graph by omission — which is exactly what this commit's HTTP
operation would otherwise have been.
IT IS A DIFFERENT ROLE FROM Sweeper, not a mode of it. Sweeper erases a set the
caller DESCRIBED; this erases rows the caller NAMED. That is what decides where
each one's safety lives: a description can be accidentally too wide, so Sweeper
carries a require-a-filter refusal; a list of ids cannot be, so this one's guard
is about the graph.
THE DEFECT. The direct route's batch path deleted the rows in one transaction
and then rewrote `[deleted:ID]` into the neighbours' text afterwards, discarding
every update error. A failure in the window left a workspace whose beads were
gone and whose descriptions still cited them by id. The existence probe, the
guard, the cascade expansion, the deletion and the rewrite are now one
transaction. WHAT THAT COSTS is written into the leaf beside the promise: the
transaction is as large as the deletion plus its neighbourhood, so a batch with
a very large neighbourhood fails whole. It is NOT Sweeper's trade (bd-hysee) —
the delete itself was already one transaction on every route — and the part that
is new is named rather than measured, which is recorded for sign-off.
TWO MORE DEFECTS the single call site removed. The one-id path held its own
transaction that removed each edge by hand, so it never reported labels, events
or orphans; and `domain.DeleteIssuesParams.EnforceCascadePolicy` and `.Force`
were declared, documented in fifteen lines describing exactly these three modes,
and READ BY NOTHING. They are deleted; the policy lives in the role now.
THE CONTRACT IS WHAT WAS DELETED, not what was reported.
backend/conformance/deleter_contract.go holds eleven cases, each citing the leaf
doc, run at all three backends with ZERO PARKS and zero divergences. Every case
that acts asserts row counts through QueryScalar rather than trusting the result
the delete reported about itself. They are TWO INDEPENDENT BODIES plus an engine
check: dolt and embeddeddolt share internal/storage/issueops.DeleteInTx and
differ only in how they reach a transaction, and the unit-of-work provider
reaches the same questions through the domain use cases. It does NOT duplicate
backend/conformance/audit_issue-lifecycle.go, which stays the right home for
`DeleteIssues` at the STORAGE seam: that suite's Factory hands back a bare
storage.DoltStorage, so the unit-of-work backend — where the guard did not exist
at all before this commit — can never run a case placed there.
`bd serve` gains POST /v0/beads/issues:delete, spec first. The dependents guard,
the all-or-nothing id resolution and the reference rewrite are the role's, so
the handler is argument validation and a projection. `cascade` and `force`
default false, which is the guarded mode; DeleteIssuesResult is not
x-go-type-pinned for the reason SweepResult is not, and a reflection test keeps
the projection honest. No page envelope, so nothing to pin in pinning.go.
USER-VISIBLE, and the CHANGELOG says so loudly: a team-server script relying on
the implicit cascade starts leaving orphans; `bd delete <one-id>` without
--force now refuses over an outside dependent, converging the direct route's
three paths onto the answer two of them already gave; the proxied `--json`
result gains `orphaned_issues`. Reasoning and the alternatives are in
/data/tmp/sd-server/AMBIGUITIES.md as A-del-1..6.
Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check
(regenerate-and-diff plus the httpapi suite) green; TestDeleterContract 11/11 at
dolt, embeddeddolt and uow; the internal/workapi delete unit tests; the
internal/storage, internal/telemetry and root layering pins;
TestConformance/Audit/issue-lifecycle and the dolt TestDeleteIssues* family
(this commit refactors DeleteIssuesInTx's guard); TestEmbeddedDelete,
TestEmbeddedDeleteJSONDependencyErrorContract, TestBurnWisps,
TestWispGCProtectsActiveWisps and TestCLI_WispGCExcludeType under
BEADS_TEST_EMBEDDED_DOLT=1; TestProxiedServerDelete{,ForceOrphans,Wisp,
Concurrent}, TestProxiedServerMolBurn and TestProxiedServerWispGC under
BEADS_TEST_PROXIED_SERVER=1; and TestProxiedLookup*.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
439 lines
20 KiB
Go
439 lines
20 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"database/sql/driver"
|
|
"encoding/json"
|
|
"errors"
|
|
"net"
|
|
"net/http"
|
|
"strconv"
|
|
"syscall"
|
|
|
|
"github.com/go-sql-driver/mysql"
|
|
|
|
"github.com/steveyegge/beads/internal/httpapi/apigen"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/storage/uow"
|
|
)
|
|
|
|
// Every non-2xx byte this server emits is an RFC 9457 problem+json document
|
|
// (apigen.Problem, generated from the spec — there is one error shape here).
|
|
// This file owns the whole mapping: sentinel error in, status + machine code
|
|
// out, matched exclusively with errors.Is/errors.As. Never `err != nil ->
|
|
// status`.
|
|
//
|
|
// SENTINEL NOTE: the mapping keys on the sentinel VALUES, never on where they
|
|
// are declared. A parallel refactor relocates the canonical Err* declarations
|
|
// into a leaf issueops package and aliases them back from internal/storage
|
|
// with the same pointers, so errors.Is keeps matching either spelling with no
|
|
// edit here. Do not re-express these rows as package-path or message checks.
|
|
|
|
// Code is the machine-readable member of the problem envelope, and the only
|
|
// member a client may dispatch on.
|
|
//
|
|
// The vocabulary is a one-way door: renaming or removing a documented
|
|
// status+code pair breaks the wire. Adding one does not, which is why clients
|
|
// are told to default-branch on unknown codes within a status class. Keep it
|
|
// at what the seven v0 operations actually need.
|
|
// at what the v0 operations actually need.
|
|
type Code string
|
|
|
|
// The v0 code vocabulary. Every value here is documented in the spec, and
|
|
// TestSpecStatusCodesMatchHandlerTable fails if the two ever disagree.
|
|
const (
|
|
// CodeInvalidArgument covers every request-validation refusal: an unknown
|
|
// query parameter, a malformed value, an invalid actor, an unparseable or
|
|
// oversized body, limit=0 under --allow-non-loopback, and the Host-header
|
|
// middleware. The 400 carries `param` and `reason` so clients never have
|
|
// to tell those cases apart by reading prose.
|
|
CodeInvalidArgument Code = "invalid_argument"
|
|
// CodeInvalidCursor is a separate code because a stale or foreign cursor
|
|
// is a normal client situation with an obvious recovery (restart paging),
|
|
// not a client bug.
|
|
CodeInvalidCursor Code = "invalid_cursor"
|
|
CodeNotFound Code = "not_found"
|
|
// CodeAlreadyClaimed carries the holder in the `assignee` extension
|
|
// member, read inside the same transaction — never parsed out of the
|
|
// sentinel's message text.
|
|
CodeAlreadyClaimed Code = "already_claimed"
|
|
CodeNotClaimable Code = "not_claimable"
|
|
// CodeBusy is retryable contention: the transaction retry budget was
|
|
// exhausted, or the in-flight request limit was saturated.
|
|
CodeBusy Code = "busy"
|
|
// CodeDBUnavailable is a retryable connectivity failure reaching the
|
|
// database.
|
|
CodeDBUnavailable Code = "db_unavailable"
|
|
CodeInternal Code = "internal"
|
|
)
|
|
|
|
// codeClientClosed is a LOG-ONLY outcome, not wire vocabulary: it is
|
|
// deliberately absent from codeStatus, from operationCodes and from the
|
|
// document, and it never reaches a response body — the client it describes has
|
|
// already gone. It exists so that the request line does not book a client
|
|
// hanging up as a server fault. See failErr.
|
|
const codeClientClosed Code = "client_closed"
|
|
|
|
// codeStatus freezes one HTTP status per code. A code that could arrive with
|
|
// two different statuses would defeat the point of dispatching on it.
|
|
var codeStatus = map[Code]int{
|
|
CodeInvalidArgument: http.StatusBadRequest,
|
|
CodeInvalidCursor: http.StatusBadRequest,
|
|
CodeNotFound: http.StatusNotFound,
|
|
CodeAlreadyClaimed: http.StatusConflict,
|
|
CodeNotClaimable: http.StatusConflict,
|
|
CodeBusy: http.StatusServiceUnavailable,
|
|
CodeDBUnavailable: http.StatusServiceUnavailable,
|
|
CodeInternal: http.StatusInternalServerError,
|
|
}
|
|
|
|
// Status returns the HTTP status frozen to c, or 0 if c is not in the v0
|
|
// vocabulary.
|
|
func (c Code) Status() int { return codeStatus[c] }
|
|
|
|
// Reason distinguishes the two client postures behind a 400
|
|
// CodeInvalidArgument, so that telling them apart never requires parsing
|
|
// `detail`. The set may grow; clients default-branch on unknown values.
|
|
type Reason string
|
|
|
|
const (
|
|
// ReasonUnknownParameter means this server does not know that parameter:
|
|
// version skew. The client degrades or falls back. It is also a client's
|
|
// only per-parameter capability probe, since `capabilities` is
|
|
// operation-level.
|
|
ReasonUnknownParameter Reason = "unknown_parameter"
|
|
// ReasonInvalidValue means the server will not act on that value:
|
|
// malformed, outside the vocabulary, or legal-but-refused in this
|
|
// server's configuration (limit=0 under --allow-non-loopback). The
|
|
// recovery is always to send something different, never to retry; the
|
|
// detail says which case it was.
|
|
ReasonInvalidValue Reason = "invalid_value"
|
|
)
|
|
|
|
// staticDetail is the ONLY `detail` a 5xx may carry. The underlying error goes
|
|
// to the server log and nowhere else: driver and dial errors routinely embed
|
|
// the DSN — go-sql-driver renders connection targets as
|
|
// user@tcp(127.0.0.1:PORT)/db, net dial errors carry the same host:port — and
|
|
// query errors can carry SQL fragments. The moment the server is bound with
|
|
// --allow-non-loopback, a verbose 5xx detail is an information-disclosure
|
|
// channel to network peers. 4xx details stay specific: they reflect the
|
|
// caller's own input back, not server internals.
|
|
var staticDetail = map[Code]string{
|
|
CodeBusy: "the server is busy; retry shortly",
|
|
CodeDBUnavailable: "database temporarily unavailable; retry",
|
|
CodeInternal: "internal server error",
|
|
}
|
|
|
|
// Retry-After values, in seconds.
|
|
const (
|
|
// retryAfterContention follows an exhausted transaction retry budget. The
|
|
// budget spans many seconds of observed write contention, so a one-second
|
|
// comeback would invite a convoy of retries that each hold a slot while
|
|
// they wait — starving reads exactly when the server is busiest.
|
|
retryAfterContention = 5
|
|
// retryAfterSaturation follows an in-flight-limit wait timeout. Slot
|
|
// pressure clears quickly.
|
|
retryAfterSaturation = 1
|
|
)
|
|
|
|
// ErrBusy reports that the in-flight request limiter refused to admit the
|
|
// request within its bounded wait. The limiter itself lands with the server;
|
|
// the sentinel lives here so the mapping owns the whole 503 vocabulary.
|
|
var ErrBusy = errors.New("server busy")
|
|
|
|
// Operation ids, matching the spec's operationId values exactly.
|
|
const (
|
|
OpHealth = "health"
|
|
OpGetContext = "getContext"
|
|
OpListReadyWork = "listReadyWork"
|
|
OpGetStats = "getStats"
|
|
OpListIssues = "listIssues"
|
|
OpGetIssue = "getIssue"
|
|
OpClaimIssue = "claimIssue"
|
|
OpListSettings = "listSettings"
|
|
OpGetSetting = "getSetting"
|
|
OpListDependencyCycles = "listDependencyCycles"
|
|
// OpListDependencies reads STORED EDGE ROWS for several issues at once.
|
|
// It is a separate operation from getIssue's embedded `dependencies`
|
|
// member because it answers per named issue, reports the ids that named
|
|
// nothing, and returns edges whose target this database holds no row for.
|
|
OpListDependencies = "listDependencies"
|
|
// OpListBlockingAnnotations reads the DERIVED blocking decoration for
|
|
// several issues at once — open blockers, issues blocked, and the parent.
|
|
// It is a separate operation from listDependencies because it answers a
|
|
// summary over two edge types with a status rule applied, where that one
|
|
// returns the stored rows and applies nothing.
|
|
OpListBlockingAnnotations = "listBlockingAnnotations"
|
|
OpCountReadyWork = "countReadyWork"
|
|
OpQueryIssues = "queryIssues"
|
|
// OpSweepIssues is the one DESTRUCTIVE operation on this surface: bulk
|
|
// clearance of closed beads from one tier, behind issueops.Sweeper.
|
|
OpSweepIssues = "sweepIssues"
|
|
// OpDeleteIssues is the other DESTRUCTIVE operation: erasure of beads the
|
|
// request NAMES, behind issueops.Deleter. It is the one operation on this
|
|
// surface whose refusals include a question about the GRAPH — a named bead
|
|
// with a dependent the request did not name — as well as about the request.
|
|
OpDeleteIssues = "deleteIssues"
|
|
// OpBatchCreateIssues creates many issues as one transaction, or none.
|
|
OpBatchCreateIssues = "batchCreateIssues"
|
|
)
|
|
|
|
// operationCodes is the per-operation problem vocabulary: exactly the codes
|
|
// that operation's handler can produce, and therefore exactly what the spec
|
|
// documents for it. TestSpecStatusCodesMatchHandlerTable asserts set-equality
|
|
// in both directions, so an undocumented emission and an unemittable
|
|
// documented status both fail CI.
|
|
//
|
|
// Two 400 invalid_argument paths are reachable on every route including
|
|
// /healthz — the Host-header middleware, and the unknown-query-parameter
|
|
// refusal every decoder performs — and both are deliberately absent from every
|
|
// row here. They are uniform rules, not per-operation behavior, and the spec
|
|
// documents them once at the document level rather than repeating them on all
|
|
// twelve operations; these rows carry what an operation produces beyond them.
|
|
// documents them once at the document level rather than repeating them on
|
|
// every operation; these rows carry what an operation produces beyond them.
|
|
// Keep the two documents in step: a row here and the document-level prose are
|
|
// the only two places that carve-out exists.
|
|
var operationCodes = map[string][]Code{
|
|
// Liveness answers from the process and touches nothing that can fail.
|
|
OpHealth: nil,
|
|
// v0 serves a startup snapshot without touching the database, so there is
|
|
// no 503 here. If a later slice makes this a DB-probing readiness
|
|
// endpoint, db_unavailable joins this row and the spec in the same change.
|
|
OpGetContext: {CodeInternal},
|
|
OpListReadyWork: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
|
|
OpListIssues: {CodeInvalidArgument, CodeInvalidCursor, CodeBusy, CodeDBUnavailable, CodeInternal},
|
|
OpGetIssue: {CodeNotFound, CodeBusy, CodeDBUnavailable, CodeInternal},
|
|
// No 400 of its own: the operation takes no parameters, so the only
|
|
// invalid_argument it can raise is the document-level unknown-query-key
|
|
// rule this table deliberately omits.
|
|
OpListSettings: {CodeBusy, CodeDBUnavailable, CodeInternal},
|
|
// No 404, and that is the operation's whole shape: a key nothing stored and
|
|
// a key stored as the empty string are one answer on this surface, so the
|
|
// only refusal a key can earn is the 400 that says it was not a key.
|
|
OpGetSetting: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
|
|
// The 400 here is this operation's own, not the document-level
|
|
// unknown-parameter rule: a malformed `skip_blocked`, and the EMPTY
|
|
// `assignee` the document refuses rather than answering with the rows that
|
|
// have no assignee.
|
|
OpGetStats: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
|
|
// The cycle sweep takes no parameters at all, so it has no 400 of its own:
|
|
// the two uniform ones above are the whole of its invalid-argument story.
|
|
OpListDependencyCycles: {CodeBusy, CodeDBUnavailable, CodeInternal},
|
|
// No not_found here, deliberately: an id that names nothing is reported in
|
|
// the response's `missing` member, so a batch keeps the answers for the ids
|
|
// that were found. A 404 would discard them.
|
|
OpListDependencies: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
|
|
// The same vocabulary as the stored-edge read beside it, and no not_found
|
|
// for a stronger version of the same reason: this operation probes no id's
|
|
// existence at all, so there is nothing it could 404 on.
|
|
OpListBlockingAnnotations: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
|
|
// The same vocabulary as the listing it sizes: it takes the same filters
|
|
// and can refuse them the same way. limit=0's mode-dependent refusal has no
|
|
// analog here because there is no limit to pass — but that was a
|
|
// CodeInvalidArgument too, so this row would not change if there were.
|
|
OpCountReadyWork: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
|
|
// The listing's vocabulary minus the cursor: this operation has none, so
|
|
// invalid_cursor cannot arise. An unparseable EXPRESSION is an
|
|
// invalid_argument on `q` rather than a code of its own — a client's
|
|
// recovery is the same as for any other malformed parameter value, and a
|
|
// code it cannot act on differently is a code it should not have to know.
|
|
OpQueryIssues: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
|
|
// The 400 here is the widest on this surface, and most of it is not this
|
|
// handler's: an unknown or malformed body member is, but the unfiltered
|
|
// durable sweep, the unrecognized tier and the malformed glob are all the
|
|
// ROLE's ErrValidation reaching the wire through failSweepErr. No 404 —
|
|
// this operation names no id — and no 409: a sweep has nothing to conflict
|
|
// with, since a bead another sweep already took is simply not in the set.
|
|
OpSweepIssues: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
|
|
// CodeNotFound is the one this operation has and the sweep does not: a
|
|
// sweep describes a set that can legitimately be empty, while a delete
|
|
// names beads and an id that resolves to nothing is a caller mistake.
|
|
OpDeleteIssues: {CodeInvalidArgument, CodeNotFound, CodeBusy, CodeDBUnavailable, CodeInternal},
|
|
OpClaimIssue: {
|
|
CodeInvalidArgument, CodeNotFound, CodeAlreadyClaimed, CodeNotClaimable,
|
|
CodeBusy, CodeDBUnavailable, CodeInternal,
|
|
},
|
|
// No not_found, and that is a decision rather than an omission. The role
|
|
// refuses an edge whose target names nothing, and that refusal is about the
|
|
// REQUEST BODY the client sent, not about a resource this operation was
|
|
// asked to address — there is no id in the path to have missed. A 404 here
|
|
// would tell a client its request went to the wrong place.
|
|
//
|
|
// No conflict code either: this operation publishes no `id` member, so no
|
|
// item can collide with a stored row and the role's ErrAlreadyExists is
|
|
// unreachable from the wire.
|
|
OpBatchCreateIssues: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
|
|
}
|
|
|
|
// Result is a problem response ready to be written: the envelope plus the
|
|
// transport-level Retry-After the code implies.
|
|
type Result struct {
|
|
Problem apigen.Problem
|
|
// RetryAfterSeconds is written as the Retry-After header when positive.
|
|
RetryAfterSeconds int
|
|
}
|
|
|
|
// WithAssignee attaches the `assignee` extension member (the current holder of
|
|
// a claimed issue). Populate it from a read in the claim's own transaction —
|
|
// never by parsing the sentinel's message fragments.
|
|
func (r Result) WithAssignee(assignee string) Result {
|
|
r.Problem.Assignee = &assignee
|
|
return r
|
|
}
|
|
|
|
// WithIssueStatus attaches the `issue_status` extension member (the issue's
|
|
// status at the moment of refusal). Same rule as WithAssignee.
|
|
func (r Result) WithIssueStatus(status string) Result {
|
|
r.Problem.IssueStatus = &status
|
|
return r
|
|
}
|
|
|
|
// WithRequestID sets the `request_id` member, the correlation id echoed in the
|
|
// request log line. It is what makes a 5xx actionable: the body carries a fixed
|
|
// static detail by design, so the id is the client's only handle on the one log
|
|
// line that has the real error. The document requires it on every problem
|
|
// response, which is why this sets it unconditionally — an id this server
|
|
// failed to mint travels as an empty string rather than as a missing required
|
|
// member.
|
|
func (r Result) WithRequestID(id string) Result {
|
|
r.Problem.RequestId = id
|
|
return r
|
|
}
|
|
|
|
func newResult(code Code, detail string) Result {
|
|
status := code.Status()
|
|
if status == 0 {
|
|
// Unreachable unless a code is added without a status; fail closed
|
|
// rather than emitting a 0 status line.
|
|
status = http.StatusInternalServerError
|
|
code = CodeInternal
|
|
detail = staticDetail[CodeInternal]
|
|
}
|
|
if static, ok := staticDetail[code]; ok {
|
|
// 5xx detail is fixed per code, whatever the caller passed.
|
|
detail = static
|
|
}
|
|
p := apigen.Problem{
|
|
Status: status,
|
|
Title: http.StatusText(status),
|
|
Code: string(code),
|
|
}
|
|
if detail != "" {
|
|
p.Detail = &detail
|
|
}
|
|
return Result{Problem: p}
|
|
}
|
|
|
|
// InvalidArgument builds the 400 for a request the server refuses to
|
|
// interpret. param names the offending query parameter, body member or header;
|
|
// pass "" only when the input has no nameable part (a body that fails to parse
|
|
// at all). detail may quote the caller's own input — it is not server state.
|
|
func InvalidArgument(param string, reason Reason, detail string) Result {
|
|
res := newResult(CodeInvalidArgument, detail)
|
|
if param != "" {
|
|
res.Problem.Param = ¶m
|
|
}
|
|
r := string(reason)
|
|
res.Problem.Reason = &r
|
|
return res
|
|
}
|
|
|
|
// InvalidCursor builds the 400 for a cursor this server did not issue, cannot
|
|
// decode, or issued under a different internal version.
|
|
func InvalidCursor() Result {
|
|
return newResult(CodeInvalidCursor, "cursor is not valid for this server; restart paging without it")
|
|
}
|
|
|
|
// NotFound builds the 404 for an id this server cannot resolve. It is one
|
|
// function rather than a literal per site so that a handler which decides a
|
|
// miss WITHOUT reading storage — an id no row could hold — is indistinguishable
|
|
// on the wire from one that read and missed. A client that could tell them
|
|
// apart would be probing which ids are well-formed.
|
|
func NotFound() Result {
|
|
return newResult(CodeNotFound, "no issue or wisp with that id")
|
|
}
|
|
|
|
// ClassifyError maps an error from the storage seam onto the wire. The caller
|
|
// is responsible for logging err: everything mapped to a 5xx deliberately
|
|
// drops the error text on the floor (see staticDetail).
|
|
func ClassifyError(err error) Result {
|
|
switch {
|
|
case err == nil:
|
|
return newResult(CodeInternal, "")
|
|
|
|
// Not-found normalization belongs in the shared read path, which folds the
|
|
// two miss shapes (a wrapped sql.ErrNoRows, and a nil issue with a nil
|
|
// error) into storage.ErrNotFound. The bare sql.ErrNoRows row below is
|
|
// defense in depth for a path that has not been normalized yet: a missing
|
|
// issue must never surface as a 500. The converse mistake — treating any
|
|
// error as a miss — stays closed, because only these two sentinels reach
|
|
// 404 and everything else falls through to 500.
|
|
case errors.Is(err, storage.ErrNotFound), errors.Is(err, sql.ErrNoRows):
|
|
return NotFound()
|
|
|
|
case errors.Is(err, storage.ErrAlreadyClaimed):
|
|
return newResult(CodeAlreadyClaimed, "issue is claimed by another actor")
|
|
|
|
case errors.Is(err, storage.ErrNotClaimable):
|
|
return newResult(CodeNotClaimable, "issue is not in a claimable state")
|
|
|
|
case errors.Is(err, ErrBusy):
|
|
res := newResult(CodeBusy, "")
|
|
res.RetryAfterSeconds = retryAfterSaturation
|
|
return res
|
|
|
|
// The retry budget is spent inside uow.RunTxResult; reaching here means it
|
|
// gave up, so the request is retryable at the client's cadence, not the
|
|
// server's.
|
|
case uow.IsSerializationError(err):
|
|
res := newResult(CodeBusy, "")
|
|
res.RetryAfterSeconds = retryAfterContention
|
|
return res
|
|
|
|
case isUnavailable(err):
|
|
res := newResult(CodeDBUnavailable, "")
|
|
res.RetryAfterSeconds = retryAfterContention
|
|
return res
|
|
|
|
default:
|
|
return newResult(CodeInternal, "")
|
|
}
|
|
}
|
|
|
|
// isUnavailable reports whether err is a failure to reach the database at all
|
|
// — the server or proxy being down, idle-stopped, or dropping connections —
|
|
// as opposed to a failure while executing a statement.
|
|
//
|
|
// The list is empirical and safe to extend: it only chooses between two 5xx
|
|
// codes that carry identical static detail, so a miss costs a less useful
|
|
// `code`, never a disclosure.
|
|
func isUnavailable(err error) bool {
|
|
// context.DeadlineExceeded satisfies net.Error, so it must be excluded
|
|
// before the net.Error test below: a tripped per-request deadline is a
|
|
// generic 500, not a claim that the database is unreachable.
|
|
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
|
return false
|
|
}
|
|
if errors.Is(err, driver.ErrBadConn) || errors.Is(err, mysql.ErrInvalidConn) {
|
|
return true
|
|
}
|
|
if errors.Is(err, syscall.ECONNREFUSED) || errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.EPIPE) {
|
|
return true
|
|
}
|
|
var netErr net.Error
|
|
return errors.As(err, &netErr)
|
|
}
|
|
|
|
// Write emits res as application/problem+json. Success bodies are written by
|
|
// their handlers; every non-2xx byte goes through here.
|
|
func Write(w http.ResponseWriter, res Result) {
|
|
h := w.Header()
|
|
h.Set("Content-Type", "application/problem+json; charset=utf-8")
|
|
if res.RetryAfterSeconds > 0 {
|
|
h.Set("Retry-After", strconv.Itoa(res.RetryAfterSeconds))
|
|
}
|
|
w.WriteHeader(res.Problem.Status)
|
|
_ = json.NewEncoder(w).Encode(res.Problem)
|
|
}
|