beads/internal/httpclient/wire/paths.go
Julian Knutsen dbaa4631ca
feat(roles): BatchGetter role and POST issues:batchGet (#7248)
* feat(roles): BatchGetter role and issues:batchGet route (S7)

Adds BatchGetter.GetMany(ids) -> {Issues, Missing}, a one-snapshot,
order-preserving, deduped, 1000-id-capped batch read, wired through all
three library legs (dolt, embedded dolt, uow) behind the existing
hook/telemetry decorator chain, plus the POST /v0/beads/issues:batchGet
HTTP route (spec, apigen, wire-shape golden, issues.batchGet capability
token). Conformance contract (RunBatchGetter*, 12 cases) passes on all
three legs against real backends. No HTTP client leg yet (waits on the
generator / PR #7247); left as a documented seam on BatchGetter's doc
comment.

CLI GetIssuesByIDs call sites are left unmigrated this slice and marked
with TODO(batchgetter) comments: every call site reads an unbounded id
list today, and GetMany's 1000-id cap has no chunking/fallback in any
caller yet, so swapping them in now would add a new, unhandled failure
mode to already-shipped CLI paths (export, import, molecule port,
ready-explain, wisp sweep).

Verified via three live-mutate guards against
internal/storage/issueops/batchget.go (disabling the cap check, dropping
the Missing append, and replacing ordered iteration with map iteration):
each turns the embedded-dolt contract red, confirming the cap, Missing
reporting, and order-preservation assertions actually catch a break.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(roles): close S7 review gaps — revision on wire, BUILD sync, handler tests

Addresses the S7 Opus review's FIX-FIRST items on BatchGetter/issues:batchGet:

HIGH
- batchGetResponse now projects apigen.BatchGetIssue (types.BatchGetIssue +
  NewBatchGetIssue), carrying `revision` per issue the way IssueDetails does;
  spec, apigen and the wire-shape golden regenerated (additive, no
  wire_revision bump).
- make bazel-sync: the 12 files missing from BUILD.bazel srcs are back in
  sync across 9 BUILD.bazel files.
- New internal/httpapi/batch_get_test.go: success incl. revision, missing
  ids, empty arrays not null, unknown member refused, missing/null ids
  refused, query parameter refused, 1001 ids refused with the full request
  reaching the role, 1000 ids accepted.

MED
- RunBatchGetterAcceptsExactlyTheCap pins the cap boundary (> vs >=).
- RunBatchGetterHydratesLabels pins Labels survive projection.
- RunBatchGetterReadsOneSnapshot renamed to
  RunBatchGetterSharesOneReadStructurally with a doc that no longer
  overclaims atomicity; a real interleaving test needs a hook on the frozen
  roleFixtureKit, out of scope here.
- Doc comments across ExecuteGetMany, GetManyResult.Issues and the
  BatchGetter interface now say hydration is labels only.

LOW
- failBatchGetErr's doc no longer claims blank entries are "already caught".
- PR #7247 references kept.

Re-ran build/vet/gofmt/lint, make api-check, make bazel-sync(-check), the
full internal/httpapi suite, and all three conformance legs (dolt via the
pinned local server, embeddeddolt, uow) plus targeted cmd/bd serve tests —
all green. Live-mutate-guard reverified: cap >=, dropping Missing from the
response, and clearing Labels each now fail the relevant test.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(roles): sync client vocabulary and repo gates with issues:batchGet

The S7 route landed on the server without the sibling tables that hold
the rest of the tree set-equal with the server's surface, so five
tests and two manifest gates went red on the PR head:

- httpclient/wire: mirror batchGetIssues into the client vocabulary,
  CLASSIFIED, not wired, the way the wire wave and #7250's
  issues.count.scope landed: OpBatchGetIssues, its issues.batchGet
  token on opCapability, its identity row, and the first-slice skew
  dimension 35 -> 36 (TestCapabilityTableMatchesTheServerRouteTable).
- httpclient/wire: BatchGetIssue is the first golden.json schema with
  a `revision` member that needs no legacy-integer tolerance — the
  route postdates #6053 and types.BatchGetIssue declares Revision a
  string, and a pre-#6053 server never advertises issues.batchGet, so
  Preflight refuses before any body is decoded. Exempt it with that
  reason in a new revisionSchemaExempt table rather than adding an
  issues[] rewrite no legacy server can reach; the gate refuses an
  entry that is both covered and exempt, a stale exemption, and an
  empty reason.
- httpclient/encode: give the oracle's role set a BatchGetter stub —
  httpapi.Listen requires the whole set, so all three oracle tests
  failed to bind.
- storage/uow: exempt IssueUseCase.GetMany from the notifying-parity
  partition as a read, the reason hook_batch_getter.go gives.
- shard manifest: place TestBatchGetterContract in the 15-shard
  embedded storage block (generator --write, incremental).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(roles): pin the BatchGetter pure tier and the spec ids caps

Review fixes, iteration 1. The review approved with no blocker or major
finding and three minors, and this commit takes all three. It changes
tests and one comment only, and every new assertion was mutation-probed
with go test -overlay.

- storage/issueops: add batchget_test.go, the database-free tier that
  FinishGetMany's doc already claimed ("pinned without a database") but
  that no test supplied. It pins:
  - the cap is checked before the blank scan (an over-cap request with
    a blank at position 0 answers *TooManyIDsError);
  - the bound is inclusive;
  - dedupe keeps the first mention, does not trim, and never writes
    through the caller's slice;
  - Issues and Missing both follow request order;
  - both slices are never nil;
  - ExecuteGetMany refuses one id repeated past the cap before any
    query (a sqlmock with no expectations).
  Ten mutants were each killed by exactly their intended test, with the
  rest of the package green: last-mention, sort, trim, in-place dedupe,
  blank-before-cap, >=, nil Missing, nil Issues, dedupe-before-validate
  and validate-after-query.
- httpapi: TestSpecDefaultsMatchSharedConstants now checks ids.maxItems
  against the enforced bound on the two request bodies that carry an
  `ids` list: batchGetIssues against issueops.MaxGetManyIDs, and
  deleteIssues against maxDeleteIDs. Each body is reached through its
  operation's own requestBody $ref. Setting either constant to 999 turns
  only this test red. The spec's other list caps (batch
  create/close/apply items, dependency edge lists) stay ungated, as
  before.
- cmd/bd/serve.go: the batchGetter field comment said its accessor
  "does NOT recurse through the hook decorator". HookFiringStore.
  BatchGetter does recurse to the inner getter; it just doesn't wrap
  the result. The comment now says that.

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 Sonnet 5 <noreply@anthropic.com>
2026-10-05 12:09:18 -07:00

222 lines
8.7 KiB
Go

// Contributed by gascity from bd-enterprise (internal/enterprise/httpstore/wire/paths.go@49d1df2f6)
// to OSS beads under the MIT license.
package wire
import (
"fmt"
"net/url"
"strings"
)
// The operation ids, spelled exactly as the document's operationId values and
// as internal/httpapi's Op* constants. They are redeclared here rather than
// imported because internal/httpapi is the SERVER — importing it would drag the
// storage engine into every process that only wants to talk to one.
// TestOperationIdsMatchTheServerRouteTable is the seam that keeps the two
// spellings from drifting.
const (
OpHealth = "health"
OpGetContext = "getContext"
OpListReadyWork = "listReadyWork"
OpCountReadyWork = "countReadyWork"
OpGetStats = "getStats"
OpListIssues = "listIssues"
OpQueryIssues = "queryIssues"
OpGetIssue = "getIssue"
OpClaimIssue = "claimIssue"
OpCloseIssue = "closeIssue"
OpReopenIssue = "reopenIssue"
OpUpdateIssue = "updateIssue"
OpSweepIssues = "sweepIssues"
OpDeleteIssues = "deleteIssues"
OpBatchCreateIssues = "batchCreateIssues"
OpBatchCloseIssues = "batchCloseIssues"
OpClaimNextIssue = "claimNextIssue"
OpReleaseIssue = "releaseIssue"
OpCountIssues = "countIssues"
OpCreateIssue = "createIssue"
OpApplyBatch = "applyBatch"
OpCompareAndSetMetadata = "compareAndSetMetadata"
OpListEvents = "listEvents"
OpWatchEvents = "watchEvents"
OpListSettings = "listSettings"
OpGetSetting = "getSetting"
OpSetSetting = "setSetting"
OpUnsetSetting = "unsetSetting"
OpListDependencies = "listDependencies"
OpListBlockingAnnotations = "listBlockingAnnotations"
OpGetDependencyTree = "getDependencyTree"
OpCountDependencyEdges = "countDependencyEdges"
OpListRelatedIssues = "listRelatedIssues"
OpAddComment = "addComment"
OpListDependencyCycles = "listDependencyCycles"
OpAddDependencies = "addDependencies"
OpRemoveDependency = "removeDependency"
OpListMemories = "listMemories"
OpRememberMemory = "rememberMemory"
OpGetMemory = "getMemory"
OpForgetMemory = "forgetMemory"
OpBatchGetIssues = "batchGetIssues"
)
// The paths that carry no caller-supplied segment. A path with one is built by
// the functions below, because an id has to be escaped before it can be joined.
const (
PathHealth = "/healthz"
PathContext = "/v0/beads/context"
PathReady = "/v0/beads/ready"
PathReadyCount = "/v0/beads/ready:count"
PathStats = "/v0/beads/stats"
PathIssues = "/v0/beads/issues"
PathIssuesQuery = "/v0/beads/issues:query"
PathIssuesCount = "/v0/beads/issues:count"
PathIssuesSweep = "/v0/beads/issues:sweep"
PathIssuesDelete = "/v0/beads/issues:delete"
PathIssuesBatchCreate = "/v0/beads/issues:batchCreate"
PathIssuesBatchClose = "/v0/beads/issues:batchClose"
PathIssuesClaimNext = "/v0/beads/issues:claimNext"
PathIssuesBatchApply = "/v0/beads/issues:batchApply"
PathSettings = "/v0/beads/config"
PathEvents = "/v0/beads/events"
PathEventsWatch = "/v0/beads/events:watch"
PathDependencies = "/v0/beads/dependencies"
PathDependenciesCount = "/v0/beads/dependencies:count"
PathDependenciesBlocking = "/v0/beads/dependencies/blocking"
PathDependenciesTree = "/v0/beads/dependencies/tree"
PathDependenciesCycles = "/v0/beads/dependencies/cycles"
PathDependenciesAdd = "/v0/beads/dependencies:add"
PathDependenciesRemove = "/v0/beads/dependencies:remove"
PathMemories = "/v0/beads/memories"
)
// The custom methods that ride on the issue-detail segment. The server splits
// them back off the segment its wildcard matched (internal/httpapi/routes.go,
// customMethodTarget), so the suffix must be the LAST thing in that segment and
// its colon must be literal — which is the whole reason escapeSegment escapes a
// colon inside the id itself.
const (
MethodClaim = ":claim"
MethodClose = ":close"
MethodReopen = ":reopen"
MethodRelease = ":release"
MethodCASMetadata = ":casMetadata"
)
// The sub-resource collections that hang off the issue-detail path. Unlike a
// custom method these are ORDINARY segments after the id, so the server routes
// them with a literal rather than through the custom-method dispatcher — but the
// id in front of them is still one wildcard-matched segment, which is why they
// go through the same escape.
const (
SubresourceComments = "comments"
SubresourceRelated = "related"
)
// IssuePath is the issue-detail path: GET reads it, PATCH updates it.
func IssuePath(id string) (string, error) {
seg, err := escapeSegment("issue id", id)
if err != nil {
return "", err
}
return PathIssues + "/" + seg, nil
}
// IssueMethodPath is the issue-detail path with a custom method appended to the
// final segment: /v0/beads/issues/{id}:claim and its two siblings.
func IssueMethodPath(id, method string) (string, error) {
switch method {
case MethodClaim, MethodClose, MethodReopen, MethodRelease, MethodCASMetadata:
default:
return "", fmt.Errorf("no custom method %q on the issue resource", method)
}
base, err := IssuePath(id)
if err != nil {
return "", err
}
return base + method, nil
}
// IssueCommentsPath is the comment collection an issue owns: the POST that
// appends one comment to its thread.
//
// There is no GET here on purpose. The wire publishes no comment page — the
// thread is read through `GET /v0/beads/issues/{id}?include_comments=true` — so
// a read helper on this path would name a route that does not exist.
func IssueCommentsPath(id string) (string, error) {
return issueSubresourcePath(id, SubresourceComments)
}
// IssueRelatedPath is the neighbor read anchored on one issue.
func IssueRelatedPath(id string) (string, error) {
return issueSubresourcePath(id, SubresourceRelated)
}
// issueSubresourcePath joins a literal collection onto the escaped issue
// segment.
//
// The escape matters MORE here than on the detail path, not less, and it is
// worth saying why the sub-resource does not make it safe: a slash in the id
// would push the literal onto a third segment, so `/comments` would no longer be
// the collection this request named. The server's wildcard matches exactly one
// segment, so that request 404s rather than writing to another anchor's thread —
// but only because the path shape is what it is, and escapeSegment is what keeps
// it that way for every id.
func issueSubresourcePath(id, collection string) (string, error) {
base, err := IssuePath(id)
if err != nil {
return "", err
}
return base + "/" + collection, nil
}
// SettingPath is the single-setting read path.
func SettingPath(key string) (string, error) {
seg, err := escapeSegment("setting key", key)
if err != nil {
return "", err
}
return PathSettings + "/" + seg, nil
}
// MemoryPath is the single-memory path, shared by the read and the delete.
//
// Memory keys are the widest segment on this surface — the document allows
// spaces, dots and unicode — so this is the escape that earns its keep.
func MemoryPath(key string) (string, error) {
seg, err := escapeSegment("memory key", key)
if err != nil {
return "", err
}
return PathMemories + "/" + seg, nil
}
// escapeSegment percent-escapes one caller-supplied path segment.
//
// url.PathEscape is the start of the job and not the end of it. Two characters
// it deliberately leaves alone are load-bearing here:
//
// ':' is legal in a path segment, so PathEscape keeps it — but on THIS
// surface a trailing `:verb` is a custom method the server splits off the
// segment. An id ending in ":claim" would be read as a claim of a shorter
// id, and one containing any colon makes the split ambiguous. It travels
// escaped.
// '.' survives too, and the joins below run through path.Join, which RESOLVES
// "." and ".." — a segment that is one of them would climb out of its own
// collection. Only the whole-segment case can do that, so only it is
// rewritten.
//
// An empty segment is refused rather than escaped: it would join to the
// collection path and turn a read of one resource into a read of all of them.
func escapeSegment(kind, s string) (string, error) {
if s == "" {
return "", fmt.Errorf("empty %s", kind)
}
seg := strings.ReplaceAll(url.PathEscape(s), ":", "%3A")
switch seg {
case ".":
seg = "%2E"
case "..":
seg = "%2E%2E"
}
return seg, nil
}