* feat(http): bd blocked over bd serve (blocked.list) through issueops.BlockedLister
`bd blocked` refused against an HTTP workspace: it called the legacy
GetBlockedIssues, which the HTTP backend stubs as unsupported. It now runs
one role on every route, and bd serve publishes that role.
- Role: issueops.BlockedLister.ListBlocked(BlockedRequest{ParentID, Labels,
LabelsAny, ExcludeLabels}) -> BlockedResult{Items}. One body,
internal/storage/issueops.ExecuteListBlockedInTx over the unchanged
GetBlockedIssuesInTx; labels normalized in the role (BlockedFilter);
Items never nil and in a total order (priority, created_at desc, id).
- Legs: DoltStore (read tx), EmbeddedDoltStore (read conn), uow (read unit
of work through the use case's GetBlockedIssues, so the
external-dependency uow decorator applies). Census: storage.DoltStorage
gains BlockedLister(); HookFiringStore passes it through (a read),
telemetry wraps it, uow.notifyingProvider, externaldeps.uowProvider and
httpapi.timedProvider build it.
- externaldeps.Store.BlockedLister is built over its own GetBlockedIssues,
so local `bd blocked` output is unchanged. Over a remote store it takes
the server's listing when the server advertises
policy.external_dependencies, else decorates the server's listing here
through EdgeReader and BatchGetter (decorateBlocked, factored out of
GetBlockedIssues).
- Wire: GET /v0/beads/blocked (listBlockedIssues; parent, label,
label_any, exclude_label) answering BlockedPage {items, has_more} with
the new x-go-type-pinned BlockedIssue schema, behind the new
blocked.list token. apigen and the wire-shape golden regenerated; the
golden diff is additive only, so wire_revision stays 2.
Config.BlockedLister is a required role, wired in bd serve.
- Client: httpclient.Store.BlockedLister dials through Store.dispatch, so
an older server is refused BEFORE the dial with *wire.CapabilityError
naming blocked.list. The legacy Store.GetBlockedIssues rides the role
(page and row cap applied to its answer) and leaves the unsupported
shell. Divergence ledger row F-blocked retired.
- CLI: `bd blocked` takes BlockedLister() from the store on the direct
routes and from the provider's BlockedListerSource on the proxied route;
runBlockedProxiedServer is deleted. --json output is the same rows in
the same order, [] when empty.
Tests: backend/conformance RunBlockedLister (10 cases: direct blocker,
child attributed to its blocked parent, closed blocker, wisp plane, pinned
status, parent filter, label filters with normalization, order, empty
slice, request not mutated) on dolt, embedded, uow and the served HTTP
client; httpapi handler tests (mapping, unknown/repeated params,
projection, capability); httpclient stub tests (pre-dial refusal naming
the token, encoding, projection, legacy door paging); skew and vocabulary
counts; TestE2E_BlockedOverHTTP (served `bd blocked --json` equals the
local command's after mapping ids and timestamps, member order included,
external blocker named, older-server refusal with no dial); corpus
gc-blocked re-marked and gc-blocked-parent added, both pending until the
reference server advertises blocked.list.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(blocked): pin server-side external decoration, refuse has_more, serve the legacy door over http
Review fixes for the blocked.list slice.
- Server-side external decoration is now pinned on the compositions bd
serve answers from. TestWrapUOWProviderBlockedListerNamesExternalBlockers
lists through the wrapped unit-of-work provider's own BlockedLister
accessor (the bd serve provider path) and requires an external-only row
and a mixed row to carry their external: refs; building that lister over
the inner provider fails it. TestServedBlockedListerCarriesExternalRefs-
WhenTheServerEnforces serves the store-shaped composition
(externaldeps.Store.BlockedLister, policy advertised) and requires the
operation's own answer, through the undecorated client role, to carry the
refs, and the client's decorated chain to return it unchanged; serving
the inner store's lister fails it.
- The client refuses an answer reporting has_more with the new typed
httpclient.TruncatedListingError instead of returning a short listing:
the operation has no cursor, and a caller reads a missing row as
unblocked. The legacy door inherits it.
- externaldeps.Store.GetBlockedIssues over an http store reads the extra
sources through the served roles (EdgeReader, BatchGetter) instead of the
raw GetIssuesByIDs / GetDependencyRecordsForIssues the http backend
refuses, and the decoration skips the source read when there is nothing
to load. The legacy door on the CLI chain (bd mol stale, the wisp
commands) now answers over http in both policy modes;
TestServedLegacyGetBlockedIssuesThroughTheDecorator pins it, paging
included. bd ready --explain still refuses on its other raw reads; the
CHANGELOG says so.
- Docs: the spec and the retired F-blocked ledger row state that the
listing is unpaged, bounded by the client's 32 MiB response limit
(refused, never read in part), and that has_more is refused.
- Contract: new cases for waits-for and conditional-blocks blockers, no
type exclusions (gate, epic), and a stale flag with no nameable blocker
(on the legs that can write the column: dolt, embedded; skipped
elsewhere with the reason). Order seeds explicit created_at values with
five rows tied on priority and created_at, two of them wisps, so only the
id tiebreak orders them; dropping the tiebreak now fails every run.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(blocked): bd blocked --flags, the blocked flag per id from stdin
`bd blocked --flags [--json]` reads ids from stdin, one per line (blank
lines and repeats ignored), and prints the blocked flag bd holds for each:
with --json, [{"id","is_blocked"}] in the order the ids were first given,
omitting an id that names no row on either plane, [] for no input. It is
the readiness column a consumer otherwise had to read with `bd sql`, so no
such consumer needs a local-only command.
It is the FLAG, not the listing: `bd blocked` narrows the stored flag to
rows it can name a blocker for, and --flags does not, so a row whose flag
is set with no nameable blocker reads true here and is absent from the
listing. Where the external-dependency policy applies, an unsatisfied
external: blocker sets the flag, as it keeps the row out of `bd ready`.
One library entry on every route: issueops.BlockedFlags over the route's
BlockingAnnotator (the store's accessor on dolt, embedded and HTTP, the
provider's on the proxied route). Over HTTP that is listBlockingAnnotations
with is_blocked behind dependencies.blocking.isBlocked; a server without
that token is refused before the dial, naming it. No wire change. The
listing's filter flags are refused with --flags rather than ignored.
Tests: TestE2E_BlockedFlagsOverHTTP (served JSON equals the local command's
after mapping ids to titles, unknown id omitted, repeat collapsed, [] on
empty stdin, filters refused; a stale-flagged row with no blocker reads
true and is absent from `bd blocked --json`, which fails if --flags is
derived from the listing; an older server's handshake refused naming the
token with no dial); TestProxiedServerBlocked/flags_reads_ids_from_stdin on
the proxied route; corpus gc-blocked-flags, pending until the reference
server advertises the token. CHANGELOG entry.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(blocked): bd blocked --flags --raw, the stored is_blocked column
`bd blocked --flags --raw [--json]` answers the stored is_blocked column
for each id read from stdin, exactly what reading is_blocked from the issues
and wisps tables returns, without the external-dependency policy: a row
blocked only by an unsatisfied external: ref reads false (the policy-aware
--flags reads true), and a stale flag reads true either way. Same output
shape as --flags. This lets a consumer move off a `bd sql` read of the
column with no change in what it reads. The default --flags is unchanged.
The role is taken from beneath every decorator: storage.UnwrapStore on the
direct routes, uow.UnwrapProvider on the proxied route. Over HTTP the
innermost store is the http client, whose annotation read is the server's
answer: against a server that does not advertise
policy.external_dependencies that answer is the column, and --raw is
served. A server that advertises it decorates the flag it answers, the v0
wire has no member asking it for the column, and the decorated flag cannot
be turned back into the column client-side, so --raw against such a server
is refused before the annotation read, naming the token, rather than
answered with the decorated flag. --raw without --flags is refused.
Tests: TestE2E_BlockedFlagsOverHTTP/raw_is_the_stored_column (served --raw
equals local --raw; the externally-blocked-only row reads true with --flags
and false with --raw on both; locally blocked rows agree; a stale-flagged
row reads true in both modes; --raw without --flags exits 1; a server
advertising the policy refuses --raw with no annotation request);
TestProxiedServerBlocked/flags_raw_is_the_stored_column; corpus
gc-blocked-flags-raw (pending until the reference server advertises
dependencies.blocking.isBlocked). Routing --raw through the decorated
annotator fails the e2e. CHANGELOG entry.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(changelog): bd blocked --flags --raw is for the local and proxied routes
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(blocked): give the e2e gate-kid its own priority; document --flags answers closed ids
TestE2E_BlockedOverHTTP seeded gate-parent and gate-kid at one priority, so
when both landed in the same second their order fell to the generated ids,
which differ between the local and the served workspace: the comparison
failed intermittently. gate-kid now has its own priority. Ten runs on the
embedded lane pass.
bd blocked --flags answers a closed id too, with its stored flag; a SQL read
of the column filtered on status <> 'closed' leaves it out. Said in the
command's doc and the CHANGELOG.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(blocked): apply label filters to external-only blocked rows
The external-dependency policy appends a row blocked only by an
unsatisfied external: ref after the label query has run, so --label,
--label-any and --exclude-label never judged it: bd blocked and
GET /v0/beads/blocked listed it whatever its labels, on every route.
Both decorators now filter those rows by the request's labels. The uow
decorator reads them through GetMany, chunked at MaxGetManyIDs, so their
labels are hydrated; GetIssuesByIDs left them empty, which also printed
them unlabelled on the proxied route.
Review fixes (adopt-pr apply-fixes, iteration 1):
- major #1: label filters on external-only rows in the store and uow
decorators, with absence-asserting arms in the unit, served httpclient
(server- and client-enforced policy), e2e and proxied tiers; the spec
and the role doc say such rows are narrowed like every other row.
- minor #2: the policy.external_dependencies token prose names the
blocked listing (spec, routes.go, regenerated types.gen.go).
- minor #6: SERVE_RUNBOOK and the allowUnlimited comment record the
blocked listing's unbounded whole-set answer and why.
- minor #10: BlockedLister telemetry-outermost and typed-unsupported pins
beside the ReadyCounter pair, plus the externaldeps wrap pin.
- nit #9: F-blocked names --flags --raw's refusal against a server that
applies the policy (ledger.go and the regenerated ledger doc).
- nit #11: the remote BlockedLister no longer builds a local lister it
then discards.
Review fixes (adopt-pr apply-fixes, iteration 2; the review approved at
940 with one minor and two nits, none gating):
- minor (the --flags refusal list was unpinned): the new
TestBlockedFlagsRefusesEveryListingFilter pins blockedFlagFilterFlags
to the flags blockedCmd registers, in both directions. Every
registered flag except --flags and --raw must be refused, and every
entry must name a registered flag. The test walks Flags() rather than
LocalFlags(), so it does not merge the root's persistent flags into
blockedCmd, and it skips inherited root flags and cobra's --help.
Mutants:
- four fail it: a new filter flag left off the list, a dropped
entry, a misspelled entry, and --raw added to the list;
- a simulated earlier in-process run (merged root flags plus --help)
stays green, and fails once either skip is removed.
- nit (the remote branch's span): the remote BlockedLister comment now
says why that lister is not wrapped again. The inner lister already
carries telemetry's span, so wrapping would nest a second span of the
same name. The comment also says what runs outside that span.
- nit (duplicated order comparator): left as is. finishBlockedIssues
predates this PR, so merging the two sorts would refactor existing
code with no review pass left after this one.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
796 lines
39 KiB
Go
796 lines
39 KiB
Go
// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/wire/handshake.go@49d1df2f6)
|
|
// to OSS beads under the MIT license.
|
|
package wire
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
|
|
"github.com/steveyegge/beads/internal/httpapi/apigen"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
// APIVersion is the path major this client speaks. ContextResponse.api_version
|
|
// must equal it exactly: the wire is versioned by path, so a server answering
|
|
// anything else is a server this client cannot address at all.
|
|
const APIVersion = "v0"
|
|
|
|
// baselineOps are the five operations that dispatch WITHOUT a pre-flight.
|
|
//
|
|
// They exist in every v0 release — they are the first slice — so consulting
|
|
// capabilities before them buys nothing and costs a round trip on the hot
|
|
// work-distribution path. Their errors classify by problem code like everything
|
|
// else.
|
|
//
|
|
// claimIssue is first-slice too, but it is deliberately NOT here (ga-b8ddd.11).
|
|
// A claim is a WRITE, and the handshake carries the project-identity gate;
|
|
// exempting the claim let it land against a server whose identity no longer
|
|
// matched the workspace — a silent cross-project write. Forcing its handshake
|
|
// runs the gate before the claim, at the price of one round trip every other
|
|
// write already pays. issues.claim is first-slice on every v0 server, so the
|
|
// forced handshake never turns a working claim into a capability refusal.
|
|
var baselineOps = map[string]bool{
|
|
OpHealth: true,
|
|
OpGetContext: true,
|
|
OpListReadyWork: true,
|
|
OpListIssues: true,
|
|
OpGetIssue: true,
|
|
}
|
|
|
|
// opCapability is the token each operation contributes to
|
|
// ContextResponse.capabilities. The two identity operations contribute none:
|
|
// liveness and the handshake itself are not gated by the list they publish.
|
|
//
|
|
// TestCapabilityTableMatchesTheServerRouteTable proves this table set-equal
|
|
// with the server's own, so an operation added upstream cannot arrive here
|
|
// unclassified.
|
|
var opCapability = map[string]string{
|
|
OpHealth: "",
|
|
OpGetContext: "",
|
|
OpListReadyWork: "ready.list",
|
|
OpCountReadyWork: "ready.count",
|
|
OpGetStats: "stats.get",
|
|
OpListIssues: "issues.list",
|
|
OpQueryIssues: "issues.query",
|
|
OpGetIssue: "issues.get",
|
|
OpClaimIssue: "issues.claim",
|
|
OpCloseIssue: "issues.close",
|
|
OpReopenIssue: "issues.reopen",
|
|
OpUpdateIssue: "issues.update",
|
|
OpSweepIssues: "issues.sweep",
|
|
OpDeleteIssues: "issues.delete",
|
|
OpBatchCreateIssues: "issues.batchCreate",
|
|
OpBatchCloseIssues: "issues.batchClose",
|
|
// The three operations the wire wave published while this client was being
|
|
// built. They are CLASSIFIED, not wired: the client has no accessor behind
|
|
// any of them yet, so its refusals stand — but an operation the server
|
|
// advertises and this table does not know is one the pre-flight would dial
|
|
// blind, which is the failure the set-equality gate exists to stop. The
|
|
// tokens land here in the sync that absorbs the wave; the accessors land in
|
|
// the client waves that follow.
|
|
OpClaimNextIssue: "issues.claimNext",
|
|
OpReleaseIssue: "issues.release",
|
|
OpCountIssues: "issues.count",
|
|
OpCreateIssue: "issues.create",
|
|
OpApplyBatch: "issues.batchApply",
|
|
OpCompareAndSetMetadata: "issues.casMetadata",
|
|
OpListEvents: "events.list",
|
|
OpWatchEvents: "events.watch",
|
|
OpListSettings: "config.list",
|
|
OpGetSetting: "config.get",
|
|
OpSetSetting: "config.set",
|
|
OpUnsetSetting: "config.unset",
|
|
OpListDependencies: "dependencies.list",
|
|
OpListBlockingAnnotations: "dependencies.blocking",
|
|
OpGetDependencyTree: "dependencies.tree",
|
|
OpCountDependencyEdges: "dependencies.count",
|
|
OpListRelatedIssues: "issues.related",
|
|
OpAddComment: "issues.addComment",
|
|
OpListDependencyCycles: "dependencies.cycles",
|
|
OpAddDependencies: "dependencies.add",
|
|
OpRemoveDependency: "dependencies.remove",
|
|
OpListMemories: "memories.list",
|
|
OpRememberMemory: "memories.remember",
|
|
OpGetMemory: "memories.get",
|
|
OpForgetMemory: "memories.forget",
|
|
// The batch read (upstream #7248) is CLASSIFIED, not wired, for the reason
|
|
// the block above states: the server publishes it ahead of the accessor
|
|
// that dials it, and the set-equality gate needs its token here first.
|
|
OpBatchGetIssues: "issues.batchGet",
|
|
// The stale-lease sweep, dialed by httpLeaseReclaimer. A server that
|
|
// predates it does not advertise the token, so Preflight refuses locally
|
|
// with a typed capability error instead of dialing a path the older server
|
|
// would answer as a claim of an issue called ":reclaim".
|
|
OpReclaimIssues: "issues.reclaim",
|
|
// The lease refresh, dialed by httpHeartbeater. A server that predates it
|
|
// does not advertise the token, so Preflight refuses locally with a typed
|
|
// capability error rather than dialing a route the older server lacks.
|
|
OpHeartbeatIssue: "issues.heartbeat",
|
|
// The blocked listing, dialed by httpBlockedLister. A server that
|
|
// predates it does not advertise the token, so Preflight refuses locally
|
|
// with a typed capability error naming blocked.list rather than dialing a
|
|
// route the older server lacks.
|
|
OpListBlockedIssues: "blocked.list",
|
|
// The advance-a-molecule role (molecule.go) dials it when served and
|
|
// refuses before dialing when not; it never composes a client-side copy.
|
|
OpAdvanceMolecule: "issues.advanceMolecule",
|
|
}
|
|
|
|
// CapProjectEnforce is the behavior capability the server advertises to announce
|
|
// per-request Bd-Project-Id enforcement, spelled exactly as httpapi's constant of
|
|
// the same name (held to it by TestProjectEnforceCapabilityMatchesTheServer).
|
|
// Unlike the per-operation tokens in opCapability it gates no route: it names a
|
|
// server-wide behavior, not an operation. The client does not consult it before
|
|
// stamping — the stamp is always sent and an older server simply ignores an
|
|
// unknown header — but it rides in the same ContextResponse.capabilities list, so
|
|
// the capability-union parity gate must account for it.
|
|
const CapProjectEnforce = "project.enforce"
|
|
|
|
// CapListSort is the behavior capability announcing that listIssues honors
|
|
// `sort` and `reverse`, spelled exactly as httpapi's constant of the same name
|
|
// (held to it by TestTheProjectIdentityVocabularyMatchesTheServer). Like
|
|
// CapProjectEnforce it gates no route — listIssues has its own operation token
|
|
// — it names a property of that operation, so it rides here rather than on
|
|
// opCapability.
|
|
//
|
|
// Nothing in this package reads it yet: the server surface ships first and the
|
|
// client that pushes a sort down follows. It is declared now because the
|
|
// capability-union parity gate compares this client's whole vocabulary with the
|
|
// server's, so the mirror is what makes the two land together.
|
|
const CapListSort = "issues.list.sort"
|
|
|
|
// CapCountScope is the behavior capability announcing that countIssues honors
|
|
// the four scope parameters `parent`, `no_parent`, `exclude_type` and
|
|
// `exclude_status` (upstream #7199), spelled exactly as httpapi's
|
|
// CapIssuesCountScope (held to it by TestTheProjectIdentityVocabularyMatchesTheServer).
|
|
// Like CapListSort it names parameters on an existing operation —
|
|
// issues.count is already countIssues' per-operation token — so it rides here
|
|
// rather than on opCapability.
|
|
//
|
|
// Nothing in this package reads it yet: the encoder table maps the four
|
|
// members (encode.countTable), and the count role client that dials
|
|
// countIssues is what must consult it — refusing LOCALLY with a typed
|
|
// capability error naming this token, before any network call, when a request
|
|
// populates ParentID, NoParent, ExcludeTypes or ExcludeStatus and the
|
|
// handshake snapshot does not advertise it (httpapi.CapIssuesCountScope's doc
|
|
// states that obligation and the downstream fallback it protects). It is
|
|
// declared now for the same reason CapListSort was: the capability-union
|
|
// parity gate compares this client's whole vocabulary with the server's.
|
|
const CapCountScope = "issues.count.scope"
|
|
|
|
// CapListSearch is the behavior capability announcing that listIssues honors
|
|
// `q`, `bd search`'s free text (issueops.ListRequest.Query), spelled exactly
|
|
// as httpapi's CapIssuesListSearch. The Reader's List reads it off the
|
|
// handshake snapshot and refuses a request that carries Query LOCALLY, with a
|
|
// typed capability error naming this token, when the server does not
|
|
// advertise it — so a search never dials a server that would answer
|
|
// `unknown_parameter`, and is never widened into the unsearched listing.
|
|
const CapListSearch = "issues.list.search"
|
|
|
|
// CapListNoAssignee, CapListTitle and CapListIDs are the behavior
|
|
// capabilities announcing that listIssues honors `no_assignee`, `title` and the
|
|
// repeatable `id` (`bd list --no-assignee`, `--title`, `--id`;
|
|
// issueops.ListRequest's NoAssignee, TitleSearch and IDFilter), spelled exactly
|
|
// as httpapi's CapIssuesListNoAssignee, CapIssuesListTitle and CapListIDs. The
|
|
// Reader's List reads them off the handshake snapshot and refuses a request
|
|
// carrying a member LOCALLY, with a typed capability error naming that
|
|
// member's token, when the server does not advertise it — never a round trip
|
|
// an older server answers `unknown_parameter`, never a wider listing than
|
|
// asked for.
|
|
const (
|
|
CapListNoAssignee = "issues.list.noAssignee"
|
|
CapListTitle = "issues.list.title"
|
|
CapListIDs = "issues.list.ids"
|
|
)
|
|
|
|
// CapListFilters is the behavior capability announcing that listIssues honors
|
|
// the rest of `bd list`'s filter vocabulary — the updated/closed/defer/due
|
|
// bounds, the priority range, the text and external-ref matches, the label
|
|
// pattern/regex, the spec prefix, the type and status exclusions, the mol/wisp
|
|
// types and the empty-description, no-labels, no-parent, pinned, no-pinned,
|
|
// deferred and overdue predicates — spelled exactly as httpapi's
|
|
// CapIssuesListFilters. One token for the set: the members land in one server
|
|
// build. The Reader's List refuses a request carrying any of them LOCALLY,
|
|
// naming this token, when the server does not advertise it.
|
|
const CapListFilters = "issues.list.filters"
|
|
|
|
// CapBlockingIsBlocked is the behavior capability announcing that
|
|
// listBlockingAnnotations honors `is_blocked` (issueops.BlockingRequest.
|
|
// IncludeIsBlocked), spelled exactly as httpapi's
|
|
// CapDependenciesBlockingIsBlocked. The annotator refuses a request asking
|
|
// for the flag LOCALLY, with a typed capability error naming this token, when
|
|
// the server does not advertise it, so the IsBlockedBatch read never dials a
|
|
// server that would answer `unknown_parameter`.
|
|
const CapBlockingIsBlocked = "dependencies.blocking.isBlocked"
|
|
|
|
// CapBatchApplyLarge is the behavior capability announcing that issues.batchApply
|
|
// accepts a batch larger than the compiled-in floor (100 items), up to the
|
|
// raised ceiling (1000), spelled exactly as httpapi's constant of the same name
|
|
// (held to it by TestTheBatchCapVocabularyMatchesTheServer). Like CapListSort it
|
|
// names a property of an existing operation — issues.batchApply already has its
|
|
// own per-operation token in opCapability — rather than a route of its own, so
|
|
// it rides here.
|
|
//
|
|
// Preflight reads this one: a batch over 100 items refuses locally with a typed
|
|
// capability error BEFORE any network call unless the handshake snapshot
|
|
// advertises it, in which case the ceiling is 1000. The cap is never a bare
|
|
// compiled constant for that reason — it is always read off the snapshot this
|
|
// token gates.
|
|
const CapBatchApplyLarge = "issues.batchApplyLarge"
|
|
|
|
// CapSweepWispsPlane is the behavior capability announcing that sweepIssues
|
|
// accepts `tier: "wisps-plane"` — a third tier, wider than ephemeral or
|
|
// durable, that clears the whole wisps table plus any durable bead with no
|
|
// history row — spelled exactly as httpapi's constant of the same name (held
|
|
// to it by TestTheProjectIdentityVocabularyMatchesTheServer). sweeper.go's
|
|
// tier mapping checks this token before mapping issueops.SweepWispsPlane onto
|
|
// the wire, refusing locally with a typed capability error rather than
|
|
// dialing a server that would answer the value with invalid_value. See
|
|
// W-SweepRequest.ProtectLiveDependents and W-SweepRequest.Limit (encode/
|
|
// ledger.go) for the sibling S4 members retired the same way; the tier value
|
|
// itself carries no ledger row because it widens an existing enum rather
|
|
// than adding a request member.
|
|
const CapSweepWispsPlane = "issues.sweep.wispsPlane"
|
|
|
|
// CapSweepLiveDependents is the behavior capability announcing that
|
|
// sweepIssues honors SweepRequest.protect_live_dependents and answers
|
|
// SweepSkips.live_dependent, spelled exactly as httpapi's constant of the
|
|
// same name (held to it by TestTheProjectIdentityVocabularyMatchesTheServer).
|
|
// sweeper.go reads this token before sending the field, refusing locally with
|
|
// a typed capability error rather than silently dropping the protection
|
|
// against an older server. encode/ledger.go's W-SweepRequest.ProtectLiveDependents
|
|
// row records the S4 closure of what used to be a permanent refusal.
|
|
const CapSweepLiveDependents = "issues.sweep.liveDependents"
|
|
|
|
// CapSweepLimit is the behavior capability announcing that sweepIssues honors
|
|
// SweepRequest.limit and answers SweepResult.remaining, spelled exactly as
|
|
// httpapi's constant of the same name (held to it by
|
|
// TestTheProjectIdentityVocabularyMatchesTheServer). sweeper.go reads this
|
|
// token before sending the field, refusing locally with a typed capability
|
|
// error rather than silently running an unbounded sweep against an older
|
|
// server. encode/ledger.go's W-SweepRequest.Limit row records the S4 closure
|
|
// of what used to be a permanent refusal.
|
|
const CapSweepLimit = "issues.sweep.limit"
|
|
|
|
// CapBatchApplyDepAddLineage is the behavior capability announcing that
|
|
// issues.batchApply's dep_add items accept `has_spawner` and `thread_id`,
|
|
// spelled exactly as httpapi's constant of the same name (held to it by
|
|
// TestCapabilityTableMatchesTheServerRouteTable). batchapplier.go reads this
|
|
// token before sending either field, refusing locally with a typed
|
|
// capability error rather than silently dropping graph lineage a caller
|
|
// asked to carry against an older server.
|
|
const CapBatchApplyDepAddLineage = "issues.batchApply.depAddLineage"
|
|
|
|
// CapIssuesUpdateAllowTemplate is the behavior capability announcing that
|
|
// updateIssue enforces the template read-only guard and accepts
|
|
// `allow_template` to stand it down, spelled exactly as httpapi's constant of
|
|
// the same name. Lifecycle.Update reads it from the cached handshake before
|
|
// the dial (applyTemplateGuardForServer): against a server without it, which
|
|
// predates the guard, the client refuses a template update itself on a
|
|
// pre-read and never sends `allow_template`. BatchApplier does not read it:
|
|
// an applyBatch `update` item gets no client-side check (its target resolves
|
|
// on the server), so through an older server it still edits a template
|
|
// (bd-jkp9v3).
|
|
const CapIssuesUpdateAllowTemplate = "issues.update.allowTemplate"
|
|
|
|
// CapIssuesUpdatePersistence is the behavior capability announcing that
|
|
// updateIssue accepts `patch.persistence` (issueops.IssuePatch.Persistence,
|
|
// the plane move behind `bd promote`). lifecycle.go sends the member only to
|
|
// a server advertising it, and refuses the move before the dial otherwise:
|
|
// there is no client-side fallback, because the move is one transaction on
|
|
// the server.
|
|
const CapIssuesUpdatePersistence = "issues.update.persistence"
|
|
|
|
// CapIssuesUpdateClaim is the behavior capability announcing that updateIssue
|
|
// accepts `claim` and resolves the claimed id on both planes (a wisp included),
|
|
// spelled exactly as httpapi's constant of the same name. Lifecycle.Update
|
|
// reads it from the cached handshake before the dial: with it, a claim rides
|
|
// updateIssue; without it, a claim alone goes to claimIssue (a wisp then
|
|
// refuses by name, W-ClaimRequest.Wisp) and a claim beside a patch, a guard, a
|
|
// force override or `allow_template` is refused before the dial with
|
|
// ErrUnsupported naming it.
|
|
const CapIssuesUpdateClaim = "issues.update.claim"
|
|
|
|
// CapIssuesCreateGates and CapIssuesUpdateGates are the behavior capabilities
|
|
// announcing the gate members, spelled exactly as
|
|
// httpapi's constants of the same names: await_type, await_id, timeout and
|
|
// waiters on createIssue and batchApply create items, and await_id and
|
|
// waiters on updateIssue's and batchApply update items' patch. The encoders
|
|
// send the members only to a server advertising the matching token, and
|
|
// refuse the request before the dial naming it otherwise
|
|
// (W-CreateRequest.Gates; the retired W-IssuePatch.AwaitID).
|
|
const (
|
|
CapIssuesCreateGates = "issues.create.gates"
|
|
CapIssuesUpdateGates = "issues.update.gates"
|
|
)
|
|
|
|
// CapIssuesCreateDefaultPriority is the behavior capability announcing that
|
|
// the server stores the create default priority for an ABSENT `priority`
|
|
// member on issues.create, issues.batchCreate and issues.batchApply create
|
|
// items, spelled exactly as httpapi's constant of the same name. The create
|
|
// roles read it from the cached handshake before the dial: a server without it
|
|
// reads an absent priority as P0, so against it the client sends
|
|
// issueops.DefaultCreatePriority explicitly (pinCreateDefaultPriority).
|
|
const CapIssuesCreateDefaultPriority = "issues.create.defaultPriority"
|
|
|
|
// CapCloseAutoCloseMolecule is the behavior capability announcing that
|
|
// closeIssue and batchCloseIssues accept `auto_close_molecule` and answer
|
|
// the auto-closed root, spelled exactly as httpapi's
|
|
// CapIssuesCloseAutoCloseMolecule. lifecycle.go and batchcloser.go send the
|
|
// member only when this is advertised; against an older server a close that
|
|
// asks for it is refused before it is dialed with the typed capability
|
|
// error — never a silent drop, and never a second, client-side copy of the
|
|
// rule.
|
|
const CapCloseAutoCloseMolecule = "issues.close.autoCloseMolecule"
|
|
|
|
// CapExternalDependencies is the CONDITIONAL behavior capability announcing
|
|
// that the ready, claim and close operations of this server apply bd's
|
|
// external-dependency policy themselves, spelled exactly as httpapi's constant
|
|
// of the same name.
|
|
//
|
|
// It is not in behaviorCapabilities because it is not a property of the build:
|
|
// httpapi advertises it only when the serving process composed its roles
|
|
// through the policy layer (httpapi.Config.ExternalDependencyPolicy, which
|
|
// `bd serve` sets from its actual composition), so httpapi.Capabilities() —
|
|
// the build-level list the parity gate compares against — never contains it.
|
|
//
|
|
// The externaldeps decorator (internal/storage/externaldeps) wraps the http
|
|
// store the same as any local backend (cmd/bd/storage_chain.go), and consults
|
|
// storage.ExternalDependencyPolicyProber — which httpclient.Store implements
|
|
// by checking for this token in the handshake. Against a server that
|
|
// advertises it, every policy-bearing role is the http store's own, passed
|
|
// through untouched (claim-next stays the server's atomic operation). Only a
|
|
// server that does NOT advertise it — an older bd serve, or another server —
|
|
// gets client-side enforcement: the policy is never silently skipped merely
|
|
// because the store is remote.
|
|
const CapExternalDependencies = "policy.external_dependencies"
|
|
|
|
// ClientWireRevision is the wire shape this client was built to speak and
|
|
// decode, mirroring internal/httpapi/wire_revision.go's CurrentWireRevision.
|
|
// It is sent as the Bd-Wire-Revision request header on every request
|
|
// (Client.stampRequest), so a server whose own min_client_wire_revision has
|
|
// moved past it refuses with the typed wire_revision_unsupported problem
|
|
// (problem.go's WireRevisionUnsupportedError) instead of answering with a
|
|
// shape this build was never compiled to read. It doubles as the upper bound
|
|
// of the handshake gate below: nothing compiled against revision 2 can
|
|
// promise to decode a FUTURE, non-additive revision 3.
|
|
//
|
|
// S4 added SweepRequest.protect_live_dependents, SweepRequest.limit and a
|
|
// wisps-plane SweepRequest.tier value, none of which bumped
|
|
// CurrentWireRevision (internal/httpapi/wireshape's drift gate tracks a
|
|
// request-only member's enum widening as additive, not a wire break — see
|
|
// that package's Sides/widensAdditively), so this constant stays 2 too: a
|
|
// revision-2 client (this one, and the S2 client already on main) must keep
|
|
// talking to a revision-2 server rather than refusing it over a bump nothing
|
|
// here required.
|
|
const ClientWireRevision = 2
|
|
|
|
// ClientMinWireRevision is the oldest SERVER-reported wire_revision this
|
|
// client tolerates — the other half of DESIGN.txt sec 4's "Client rule":
|
|
// handshake once per Store and gate on api_version == "v0" AND wire_revision
|
|
// within [client_min, client_max]. It is 0, not 2, because a decoded 0 means
|
|
// only that the server omitted ContextResponse.wire_revision entirely: 0 and
|
|
// 1 are permanently retired values no server implementing the member will
|
|
// ever legitimately send (see that field's doc comment), and the one thing a
|
|
// server old enough to omit it can still do is answer revision/expected_version
|
|
// tokens as bare JSON integers rather than the decimal strings upstream #6053
|
|
// standardized — a shape this package tolerates on both halves of the wire:
|
|
// problem.go's legacyRevisionFields on the error path, and
|
|
// revision_tolerance.go's serverPredatesRevisionStrings on every success-path
|
|
// response type that carries a `revision` member. There is therefore nothing
|
|
// on the low end for this client to refuse.
|
|
const ClientMinWireRevision = 0
|
|
|
|
// checkWireRevision applies the handshake half of the Client rule to a decoded
|
|
// ContextResponse, returning the typed skew refusal when the server's wire
|
|
// shape falls outside what this client build can speak, or nil when it is
|
|
// safe to proceed.
|
|
//
|
|
// Two independent conditions trigger it: the server's own
|
|
// min_client_wire_revision already exceeds what this client declares (so
|
|
// every request would earn the same wire_revision_unsupported 400 the
|
|
// Bd-Wire-Revision header invites — refusing here spends no round trip
|
|
// learning what the handshake already answered), or the server's own
|
|
// wire_revision is past ClientWireRevision (a future, non-additive wire
|
|
// change this build predates). A decoded wire_revision of 0 never trips the
|
|
// second check on its own: per ClientMinWireRevision's doc, that is the
|
|
// "omitted" signal, not a value above range.
|
|
func (c *Client) checkWireRevision(body apigen.ContextResponse) error {
|
|
switch {
|
|
case body.MinClientWireRevision > ClientWireRevision:
|
|
return &WireRevisionSkewError{
|
|
ServerURL: c.base.Redacted(),
|
|
BdVersion: stripControlRunes(body.BdVersion),
|
|
ClientWireRevision: ClientWireRevision,
|
|
ServerWireRevision: body.WireRevision,
|
|
MinClientWireRevision: body.MinClientWireRevision,
|
|
}
|
|
case body.WireRevision > ClientWireRevision:
|
|
return &WireRevisionSkewError{
|
|
ServerURL: c.base.Redacted(),
|
|
BdVersion: stripControlRunes(body.BdVersion),
|
|
ClientWireRevision: ClientWireRevision,
|
|
ServerWireRevision: body.WireRevision,
|
|
MinClientWireRevision: body.MinClientWireRevision,
|
|
}
|
|
default:
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// ErrWireRevisionSkew reports a handshake-time wire-shape mismatch this client
|
|
// cannot safely proceed past. See WireRevisionSkewError.
|
|
var ErrWireRevisionSkew = errors.New("bd serve speaks a wire revision this client does not")
|
|
|
|
// WireRevisionSkewError is DESIGN.txt sec 4's Client rule, violated: the
|
|
// server's wire shape is outside [ClientMinWireRevision, ClientWireRevision].
|
|
// It is raised by Handshake itself, from a 200 ContextResponse, which is what
|
|
// separates it from WireRevisionUnsupportedError (problem.go) — that one is
|
|
// the SERVER refusing a request with a 400 after reading this client's own
|
|
// declared Bd-Wire-Revision header; this one is the CLIENT declining to
|
|
// proceed after reading the server's.
|
|
type WireRevisionSkewError struct {
|
|
ServerURL string
|
|
BdVersion string
|
|
// ClientWireRevision is this build's own declared revision.
|
|
ClientWireRevision int
|
|
// ServerWireRevision is the server's ContextResponse.wire_revision, decoded
|
|
// as-is (0 means the server omitted the member; see ClientMinWireRevision).
|
|
ServerWireRevision int
|
|
// MinClientWireRevision is the server's ContextResponse.min_client_wire_revision.
|
|
MinClientWireRevision int
|
|
}
|
|
|
|
func (e *WireRevisionSkewError) Error() string {
|
|
if e.MinClientWireRevision > e.ClientWireRevision {
|
|
return fmt.Sprintf("bd serve at %s (bd_version %s) requires a client wire revision of at least %d; this client speaks %d",
|
|
e.ServerURL, e.BdVersion, e.MinClientWireRevision, e.ClientWireRevision)
|
|
}
|
|
return fmt.Sprintf("bd serve at %s (bd_version %s) speaks wire revision %d, newer than any shape this client build knows how to decode (max %d)",
|
|
e.ServerURL, e.BdVersion, e.ServerWireRevision, e.ClientWireRevision)
|
|
}
|
|
|
|
func (e *WireRevisionSkewError) Unwrap() error { return ErrWireRevisionSkew }
|
|
|
|
// behaviorCapabilities mirrors the server's own behavior-token set (httpapi's
|
|
// behaviorCapabilities): the advertised tokens that name a server-wide behavior
|
|
// rather than an operation. TestCapabilityTableMatchesTheServerRouteTable proves
|
|
// union(opCapability tokens, this) set-equal with httpapi.Capabilities(), which is
|
|
// what makes the server change and this client change land together: the parity
|
|
// test goes red the moment one ships without the other.
|
|
var behaviorCapabilities = []string{
|
|
CapProjectEnforce, CapBatchApplyLarge, CapListSort, CapCountScope,
|
|
CapSweepWispsPlane, CapSweepLiveDependents, CapSweepLimit,
|
|
CapBatchApplyDepAddLineage, CapIssuesUpdateAllowTemplate, CapIssuesCreateDefaultPriority,
|
|
CapCloseAutoCloseMolecule, CapListSearch,
|
|
CapListNoAssignee, CapListTitle, CapListIDs, CapIssuesUpdatePersistence, CapBlockingIsBlocked, CapIssuesUpdateClaim,
|
|
CapIssuesCreateGates, CapIssuesUpdateGates, CapListFilters,
|
|
}
|
|
|
|
// CapabilityFor reports the capability token gating op, and whether op is on
|
|
// this client's map at all. An operation with no token — liveness, the
|
|
// handshake — reports ("", true).
|
|
func CapabilityFor(op string) (string, bool) {
|
|
token, ok := opCapability[op]
|
|
return token, ok
|
|
}
|
|
|
|
// IsBaseline reports whether op dispatches without a capability pre-flight.
|
|
func IsBaseline(op string) bool { return baselineOps[op] }
|
|
|
|
// Snapshot is the parsed handshake: one ContextResponse and its capability list
|
|
// indexed for lookup.
|
|
type Snapshot struct {
|
|
Context apigen.ContextResponse
|
|
caps map[string]struct{}
|
|
}
|
|
|
|
// Has reports whether the server advertised token.
|
|
func (s *Snapshot) Has(token string) bool {
|
|
_, ok := s.caps[token]
|
|
return ok
|
|
}
|
|
|
|
// Capabilities is the advertised token list, sorted, as a copy.
|
|
func (s *Snapshot) Capabilities() []string {
|
|
out := make([]string, 0, len(s.caps))
|
|
for token := range s.caps {
|
|
out = append(out, token)
|
|
}
|
|
slices.Sort(out)
|
|
return out
|
|
}
|
|
|
|
type handshakeCache struct {
|
|
mu sync.Mutex
|
|
snap *Snapshot
|
|
}
|
|
|
|
// Health drives the liveness probe. It is the one operation served with no
|
|
// credential, and it stays 200 while the database is wedged — so a green health
|
|
// check says the process is up and nothing more.
|
|
func (c *Client) Health(ctx context.Context) error {
|
|
var out apigen.Health
|
|
return c.Do(ctx, Request{Op: OpHealth, Method: http.MethodGet, Path: PathHealth}, &out)
|
|
}
|
|
|
|
// GetContext fetches the startup snapshot with no caching and no gates. Callers
|
|
// that want the process-wide, gated, identity-checked one want Handshake.
|
|
func (c *Client) GetContext(ctx context.Context) (apigen.ContextResponse, error) {
|
|
var out apigen.ContextResponse
|
|
err := c.Do(ctx, Request{Op: OpGetContext, Method: http.MethodGet, Path: PathContext}, &out)
|
|
return out, err
|
|
}
|
|
|
|
// Handshake fetches the context once and caches it for the life of the client,
|
|
// applying the two gates that must not be skipped: api_version equality and, if
|
|
// the workspace recorded one, project identity.
|
|
//
|
|
// The fetch is lazy — it happens on the first post-baseline dispatch, not at
|
|
// open — so a `bd ready` against a server that serves only the baseline costs
|
|
// no extra round trip. A FAILED handshake is not cached: a server that was down
|
|
// when the first post-baseline command ran must not poison the rest of the
|
|
// process.
|
|
func (c *Client) Handshake(ctx context.Context) (*Snapshot, error) {
|
|
c.handshake.mu.Lock()
|
|
defer c.handshake.mu.Unlock()
|
|
if c.handshake.snap != nil {
|
|
return c.handshake.snap, nil
|
|
}
|
|
|
|
body, err := c.GetContext(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if body.ApiVersion != APIVersion {
|
|
return nil, &APIVersionError{ServerURL: c.base.Redacted(), Got: body.ApiVersion, Want: APIVersion}
|
|
}
|
|
// The Client rule's other half (DESIGN.txt sec 4), run right after the
|
|
// api_version gate and before the identity gate: a server this client
|
|
// cannot decode is not a server worth reporting a wrong-project diagnosis
|
|
// against either, and api_version is the coarser, cheaper check of the two.
|
|
if err := c.checkWireRevision(body); err != nil {
|
|
return nil, err
|
|
}
|
|
if c.expectID != "" && body.ProjectId != c.expectID {
|
|
// These three are server-controlled and end up in an error rendered to a
|
|
// terminal — often through a per-id write sink (bd close/reopen/update)
|
|
// that bypasses the CLI's display-layer strip — so their control runes are
|
|
// removed at construction, the same source-layer strip mapProblem applies.
|
|
// RepoRoot renders via %s (raw); Got and Database render via %q (already
|
|
// escaped), stripped too so a future Error() change cannot reintroduce the
|
|
// leak. Expected is the workspace's own pinned id, not server-controlled.
|
|
//
|
|
// repo_root is OPTIONAL on the wire, so the generated member is a pointer;
|
|
// an absent one is the empty string here, which is exactly what Error()
|
|
// already reads as "that server disclosed no root" (it omits the whole
|
|
// parenthetical when Database and RepoRoot are both empty).
|
|
return nil, &ProjectMismatchError{
|
|
ServerURL: c.base.Redacted(),
|
|
Expected: c.expectID,
|
|
Got: stripControlRunes(body.ProjectId),
|
|
Database: stripControlRunes(body.Database),
|
|
RepoRoot: stripControlRunes(deref(body.RepoRoot)),
|
|
}
|
|
}
|
|
|
|
caps := make(map[string]struct{}, len(body.Capabilities))
|
|
for _, token := range body.Capabilities {
|
|
caps[token] = struct{}{}
|
|
}
|
|
c.handshake.snap = &Snapshot{Context: body, caps: caps}
|
|
return c.handshake.snap, nil
|
|
}
|
|
|
|
// ServerContext is the handshake as the STORE's transport seam spells it: one
|
|
// gated, cached, identity-checked snapshot per process.
|
|
//
|
|
// It exists so a *Client satisfies that seam directly rather than through an
|
|
// adapter every build would have to write identically. The pointer is into the
|
|
// cache and the caller must treat it as read-only — the same rule Handshake's
|
|
// Snapshot carries, for the same reason.
|
|
func (c *Client) ServerContext(ctx context.Context) (*apigen.ContextResponse, error) {
|
|
snap, err := c.Handshake(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &snap.Context, nil
|
|
}
|
|
|
|
// Preflight applies the two-speed policy to op, and is the call every dispatch
|
|
// site makes before building a request.
|
|
//
|
|
// A baseline operation returns immediately. Every other operation forces the
|
|
// handshake and checks its token, because an unrouted path on an older server
|
|
// answers a bare 404 that is INDISTINGUISHABLE from an entity's not_found — the
|
|
// version-skew signal would arrive spelled as "no such issue". Consulting the
|
|
// advertised list is the only way to tell the two apart, and it has to happen
|
|
// before the dial.
|
|
func (c *Client) Preflight(ctx context.Context, op string) error {
|
|
token, known := CapabilityFor(op)
|
|
if !known {
|
|
return fmt.Errorf("no such v0 operation %q", op)
|
|
}
|
|
if IsBaseline(op) || token == "" {
|
|
return nil
|
|
}
|
|
snap, err := c.Handshake(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if snap.Has(token) {
|
|
return nil
|
|
}
|
|
// BdVersion is server-controlled and reaches the case-2 taxonomy text AND a
|
|
// per-id write sink that bypasses the display-layer strip, so its control runes
|
|
// are removed at construction (Op and Capability are this client's own known
|
|
// strings; Capabilities is a token-membership set, never rendered as free text).
|
|
return &CapabilityError{
|
|
Op: op,
|
|
Capability: token,
|
|
ServerURL: c.base.Redacted(),
|
|
BdVersion: stripControlRunes(snap.Context.BdVersion),
|
|
Capabilities: snap.Capabilities(),
|
|
}
|
|
}
|
|
|
|
// ErrCapabilityAbsent reports that the server does not advertise the capability
|
|
// an operation needs.
|
|
var ErrCapabilityAbsent = errors.New("bd serve does not advertise the capability this operation needs")
|
|
|
|
// CapabilityError is the typed form of that refusal. It carries what the
|
|
// refusal taxonomy's case-2 text names — the server, its version, and the
|
|
// tokens it DOES advertise — so the rendering layer parses nothing.
|
|
type CapabilityError struct {
|
|
Op string
|
|
Capability string
|
|
ServerURL string
|
|
BdVersion string
|
|
Capabilities []string
|
|
}
|
|
|
|
func (e *CapabilityError) Error() string {
|
|
return fmt.Sprintf("bd serve at %s (bd_version %s) does not advertise capability %q, which %s requires",
|
|
e.ServerURL, e.BdVersion, e.Capability, e.Op)
|
|
}
|
|
|
|
// Unwrap returns both arms, so a caller holding only a role interface can
|
|
// classify a version-skew refusal the same way as any other unsupported
|
|
// capability.
|
|
//
|
|
// errors.Is(err, ErrCapabilityAbsent) stays the precise diagnosis — this
|
|
// server, this token absent, this op — and errors.As(err, *issueops.ErrUnsupported)
|
|
// (equally storage.ErrUnsupported: both are the SAME aliased type, see
|
|
// beadserrors.ErrUnsupported) now also reaches it, because a backend that
|
|
// cannot serve an operation is exactly what a capability-absent server is from
|
|
// the caller's side of the role contract. The two are not in tension: the
|
|
// ledger-refusal twin of this (InexpressibleError, in package httpclient) earns
|
|
// its *storage.ErrUnsupported arm the same way, off a value this client itself
|
|
// decided to withhold rather than a server's version — Unwrap is what lets one
|
|
// errors.As site in a role catch both without caring which.
|
|
func (e *CapabilityError) Unwrap() []error {
|
|
return []error{ErrCapabilityAbsent, &issueops.ErrUnsupported{Op: e.Op, Backend: "http", Capability: e.Capability}}
|
|
}
|
|
|
|
// NewCapabilityError builds the capability-absent refusal for a behavior the
|
|
// caller checked itself, off a handshake it already holds, rather than for an
|
|
// operation Preflight checked. The server-controlled version is stripped of
|
|
// control runes the way Preflight strips it, because the refusal reaches a
|
|
// terminal through sinks that bypass the display-layer strip.
|
|
func NewCapabilityError(op, token, serverURL string, ctx *apigen.ContextResponse) *CapabilityError {
|
|
e := &CapabilityError{Op: op, Capability: token, ServerURL: serverURL}
|
|
if ctx != nil {
|
|
e.BdVersion = stripControlRunes(ctx.BdVersion)
|
|
e.Capabilities = append([]string(nil), ctx.Capabilities...)
|
|
slices.Sort(e.Capabilities)
|
|
}
|
|
return e
|
|
}
|
|
|
|
// ErrAPIVersion reports a server on a path major this client cannot address.
|
|
var ErrAPIVersion = errors.New("bd serve speaks a different api_version")
|
|
|
|
// APIVersionError names both versions, because neither alone tells an operator
|
|
// which side to move.
|
|
type APIVersionError struct {
|
|
ServerURL string
|
|
Got string
|
|
Want string
|
|
}
|
|
|
|
func (e *APIVersionError) Error() string {
|
|
return fmt.Sprintf("bd serve at %s serves api_version %q; this client speaks %q", e.ServerURL, e.Got, e.Want)
|
|
}
|
|
|
|
func (e *APIVersionError) Unwrap() error { return ErrAPIVersion }
|
|
|
|
// ErrInvalidProjectID reports that the workspace's pinned project id is not a
|
|
// value that can be sent as the Bd-Project-Id header on every request.
|
|
var ErrInvalidProjectID = errors.New("pinned project id is not a valid header value")
|
|
|
|
// InvalidProjectIDError is the loud refusal New raises when the pinned project id
|
|
// cannot be stamped. The id comes from the workspace's sidecar, recorded by
|
|
// `bd connect`, and it is stamped on EVERY request — so a corrupt one is caught
|
|
// once, at open, rather than skipped (which would leave the workspace unenforced)
|
|
// or deferred to a per-request transport failure. The offending value is rendered
|
|
// %q so its own bad bytes — the reason it is invalid — cannot inject into the
|
|
// error text on its way to a terminal.
|
|
type InvalidProjectIDError struct {
|
|
ServerURL string
|
|
ProjectID string
|
|
}
|
|
|
|
func (e *InvalidProjectIDError) Error() string {
|
|
return fmt.Sprintf("the project id %q pinned for the workspace connected to bd serve at %s is not a valid %s header value; re-run bd connect to re-record the workspace's identity from its sidecar",
|
|
e.ProjectID, e.ServerURL, ProjectIDHeader)
|
|
}
|
|
|
|
func (e *InvalidProjectIDError) Unwrap() error { return ErrInvalidProjectID }
|
|
|
|
// ErrProjectMismatch reports that the server owns a different workspace.
|
|
var ErrProjectMismatch = errors.New("bd serve owns a different workspace")
|
|
|
|
// ProjectMismatchRecovery is the one action that resolves a wrong-server
|
|
// mismatch: point the workspace back at the server that owns it. There is no
|
|
// local database to reconcile — bd doctor and bd bootstrap have nothing to fix
|
|
// on an http workspace — so reconnecting IS the whole recovery. It is exported
|
|
// so cmd/bd's pre-write identity check can render the same guidance the
|
|
// post-baseline read path already surfaces (design D1/D6) without restating the
|
|
// string in a second place that could drift.
|
|
const ProjectMismatchRecovery = "re-run bd connect against the server that owns this workspace"
|
|
|
|
// ProjectMismatchError is the wrong-server diagnostic. It names both project
|
|
// ids AND the server's own database and repo root, because "the ids differ" does
|
|
// not tell an operator WHICH wrong server answered — and on a shared host that
|
|
// is the whole question.
|
|
type ProjectMismatchError struct {
|
|
ServerURL string
|
|
Expected string
|
|
Got string
|
|
Database string
|
|
RepoRoot string
|
|
}
|
|
|
|
func (e *ProjectMismatchError) Error() string {
|
|
var b strings.Builder
|
|
fmt.Fprintf(&b, "bd serve at %s owns project %q, but this workspace expects %q", e.ServerURL, e.Got, e.Expected)
|
|
if e.Database != "" || e.RepoRoot != "" {
|
|
fmt.Fprintf(&b, " (that server serves database %q from %s)", e.Database, e.RepoRoot)
|
|
}
|
|
b.WriteString("; " + ProjectMismatchRecovery)
|
|
return b.String()
|
|
}
|
|
|
|
func (e *ProjectMismatchError) Unwrap() error { return ErrProjectMismatch }
|
|
|
|
// BatchTooLargeError is a locally-refused issues:batchApply plan: the item
|
|
// count exceeds issueops.MaxApplyBatchItems, the absolute ceiling every v0
|
|
// server enforces regardless of capability (internal/httpapi's
|
|
// maxApplyBatchItems). ApplyBatch (writes.go) raises it before any network
|
|
// call — never dialing a plan this large — the same way Preflight never
|
|
// dials an operation the server has not advertised. It lives here rather
|
|
// than beside ApplyBatch because every exported method in writes.go is swept
|
|
// by TestEveryOperationMethodRoutesThroughTheSharedDispatch as an operation
|
|
// dispatch method; this type's two methods are not one.
|
|
//
|
|
// It unwraps to issueops.ErrValidation, the sentinel a server's own 400 on
|
|
// the same oversized plan would classify as, had the request been allowed to
|
|
// reach it.
|
|
type BatchTooLargeError struct {
|
|
Op string
|
|
ServerURL string
|
|
Count int
|
|
Limit int
|
|
}
|
|
|
|
func (e *BatchTooLargeError) Error() string {
|
|
return fmt.Sprintf("%s: a plan of %d items exceeds the %d-item ceiling bd serve at %s enforces; split it into requests of %d or fewer",
|
|
e.Op, e.Count, e.Limit, e.ServerURL, e.Limit)
|
|
}
|
|
|
|
func (e *BatchTooLargeError) Unwrap() error { return issueops.ErrValidation }
|