feat(issueops): put multi-id bd dep list behind the EdgeReader role (bd-nhsno)
`bd dep list a b c --direction=down` asks a different question from every
other dep read: it answers with RAW EDGE ROWS keyed by source, for many
anchors at once, and it has to say per anchor whether that anchor exists.
Both routes answered it off-role — the direct one out of
GetDependencyRecordsForIssues, the proxied one out of a unit of work — and
neither could tell "this issue has no dependencies" from "there is no such
issue".
THE ROLE. Relations is the near sibling and it cannot answer this. It is
SINGLE-ANCHOR, it answers with the ISSUES on the far end of an anchor's
edges, and an edge whose target this database has no row for — an
`external:` reference, an id in another repository — is silently not a
neighbor. A missing anchor is ErrNotFound there, which a batch cannot use
without discarding the anchors it did find. Different answer shape,
different miss policy, different arity: three, so a new role and a new
accessor rather than a second Relations method. Q12 confirmed the split
against merging it with BlockingAnnotator, which answers a derived
best-effort decoration rather than stored rows.
The direction is OUTGOING only and there is no parameter for it. The inbound
bulk read is a different read against a different key with its own
cross-table de-duplication, and no front door asks for it; a direction
nothing sets would be a promise nothing checks.
TWO DEFECTS THE ADOPTION FIXES, both of them the same shape — a silent
change of JSON document:
- the KNOWN DEFECT. The direct route's batched read fell through to the
hydrated neighbor listing on ANY error, so a transient failure turned
`bd dep list a b --json` from an array of dependency records into an
array of ISSUES, with no error and no warning.
- the same fall-through fired whenever routing split the anchors across
stores, so a cross-rig batch emitted that other document every time. The
role is reached per store now and the answers merge back into argument
order, so a routed batch and a local one have one shape.
Also fixed on both routes: `--type` used to test emptiness BEFORE filtering,
so an anchor whose every edge the filter rejected printed a header with no
rows under it. The role filters, so it prints "has no dependencies".
USER-VISIBLE, approved in the Q11 batch: PROXIED `bd dep list` NOW REPORTS
GHOST ANCHORS. It used to hand the raw arguments to the dependency use case,
which keys its answer by source and has no entry for an id that names
nothing, so a typo printed "<id> has no dependencies" and a script read a
clean graph. The role probes each anchor, so a typo now prints the warning
the direct route has always printed for an argument it could not resolve —
on stderr, in both modes, which is what leaves `--json` the flat array of
dependency records the command documents. The proxied route still resolves
nothing: ids go to the role exactly as the caller spelled them, because that
route has never done partial-id resolution.
One behaviour had no prior decision behind it and is recorded as Q15 rather
than chosen quietly: a repeated anchor now collapses onto its first mention,
where the old loop over a keyed map printed it twice.
CONFORMANCE. backend/conformance/edge_reader_contract.go holds fourteen
cases, each citing the leaf doc by line, run at all three implementations
with ZERO parks. They are TWO independent bodies plus an engine check, not
three: dolt and embeddeddolt both call storage/issueops.ExecuteEdgeRead
inside their own read transaction, and the unit-of-work provider is the
second body — it probes existence through two batched by-id use-case reads
where the stores run one batched EXISTS over both tables.
The store-backed body is an InTx function rather than an
internal/workapi/store<role> package, which is a documented deviation from
the twelve-step checklist and the reason is Relations': the anchor probe and
the edge read must share ONE transaction, or an anchor can be reported
missing by a probe that raced a create the edge read then saw. That cannot
be expressed above storage.DoltStorage. engdocs/ADDING_AN_ISSUEOPS_ROLE.md
now names that variant, including why it needs no depguard entry — the
shared function takes a transaction, so no front door can call it.
HTTP. GET /v0/beads/dependencies is new canonical surface, spec written
first and the types generated from it. `items` is an array of the already
x-go-type-pinned `Dependency`, so the CLI's `--json` and this body stay one
compatibility domain; the new `DependencyEdges` envelope carries no allOf,
so the oapi-codegen v2.6.0 pin-dropping trap does not apply, and the
generated `Dependency` is still an alias. A ghost anchor is on `missing`
rather than a 404, for the reason the role reports it per anchor. There is
no `limit` and no cursor: `bd dep list` has none either, so the QUESTION is
bounded instead — at most 100 `issue_id` values — which bounds the work
without truncating an answer a client could not then page.
httpapi.Config's roles source grows from two roles to three, and Listen
refuses a partially-set set for the reason it already refused a half-set
pair: the missing role is a nil dereference in a handler on a live server.
Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check
clean; TestEdgeReaderContract green at dolt (14/14), embeddeddolt (14/14)
and uow (14/14); ./internal/httpapi green; TestCorpusGolden green, so the
committed `bd dep list --json` fixture is byte-identical; TestEmbeddedDep
and TestProxiedServerDep2 green with their gates set; TestProxiedLookup
green.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
bbb44b3996
commit
b6b319b981
33 changed files with 2522 additions and 136 deletions
503
backend/conformance/edge_reader_contract.go
Normal file
503
backend/conformance/edge_reader_contract.go
Normal file
|
|
@ -0,0 +1,503 @@
|
|||
package conformance
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// This file holds the contract every implementation of publicops.EdgeReader
|
||||
// must satisfy. Each case asserts what issueops/edgereader.go PROMISES, cited
|
||||
// by line, rather than what any one backend happens to do today; a backend that
|
||||
// disagrees is parked at its own wiring site with skipKnownDivergence so the
|
||||
// case still runs on the ones that agree.
|
||||
//
|
||||
// There are three wirings — the server-backed store, the embedded store and the
|
||||
// unit-of-work provider — and TWO BODIES, not three. dolt and embeddeddolt both
|
||||
// call storage/issueops.ExecuteEdgeRead inside their own read transaction, so
|
||||
// they are one vote plus an engine check; the unit-of-work provider is the
|
||||
// second, and it is a genuinely different body: it probes existence through two
|
||||
// batched by-id use-case reads instead of a batched EXISTS over the two tables.
|
||||
// What all three share is ValidateEdgeReadRequest, EdgeReadAnchors and
|
||||
// FinishEdgeRead — the request rules, the de-duplication and the ordering — so
|
||||
// what these cases can catch below those three is the EXECUTION half: which
|
||||
// plane each seam probes, which table it reads edges from, and whether the two
|
||||
// see one snapshot.
|
||||
//
|
||||
// EVERY CASE NAMES THE EXACT IDS IT SEEDED. The three fixtures share one
|
||||
// database per suite and the two store fixtures share it with every other
|
||||
// role's cases, so an assertion that read "every anchor" would be an assertion
|
||||
// about the whole workspace and would fail the moment a sibling suite seeded a
|
||||
// row. Naming the anchors also keeps the expected answers small enough to write
|
||||
// literally.
|
||||
//
|
||||
// What is deliberately NOT here:
|
||||
// - the mapping from `bd dep list`'s arguments to a request, which is the
|
||||
// command's job;
|
||||
// - the INBOUND direction, which this role does not have (edgereader.go:157-164
|
||||
// says why) and which Relations answers hydrated for one anchor;
|
||||
// - anything about the dependency TARGET's existence, which this role does
|
||||
// not probe (edgereader.go:117-121).
|
||||
|
||||
// EdgeReaderFixture supplies adapter-specific storage access for the
|
||||
// stored-edge assertions. Every field is named and typed exactly like the
|
||||
// per-backend roleFixtureKit hook it is filled from, so a wiring is kit plus
|
||||
// accessor plus prefix with no adapter in between.
|
||||
type EdgeReaderFixture struct {
|
||||
// IssuePrefix namespaces the ids each assertion seeds, so several of them
|
||||
// can share one database.
|
||||
IssuePrefix string
|
||||
EdgeReader publicops.EdgeReader
|
||||
// CreateIssue seeds a durable issue in the issues plane.
|
||||
CreateIssue func(context.Context, *types.Issue, string) error
|
||||
// CreateWisp seeds an ephemeral issue in the wisps plane. It is a separate
|
||||
// field rather than an Ephemeral flag on CreateIssue because the three
|
||||
// adapters reach the two planes through different verbs.
|
||||
CreateWisp func(context.Context, *types.Issue, string) error
|
||||
// AddDependency seeds ONE edge, routed to the plane the edge's source lives
|
||||
// in.
|
||||
AddDependency func(context.Context, *types.Dependency, string) error
|
||||
// CountHistory reports how many history entries the fixture's branch has.
|
||||
// A nil hook means "this backend cannot observe history", and the case that
|
||||
// needs it SKIPS with that reason rather than passing quietly.
|
||||
CountHistory func(context.Context) (int, error)
|
||||
}
|
||||
|
||||
// RunEdgeReaderAnswersOnePerAnchorInRequestOrder pins edgereader.go:127-133:
|
||||
// one entry per requested id, in the order the request named them.
|
||||
//
|
||||
// The ids are seeded in the REVERSE of the order the request asks for them, so
|
||||
// a body that returned the storage seam's natural order — which is ascending by
|
||||
// source id, because that is what the batched read's ORDER BY gives — would
|
||||
// fail here rather than passing by coincidence.
|
||||
func RunEdgeReaderAnswersOnePerAnchorInRequestOrder(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
first := fixture.IssuePrefix + "-order-c"
|
||||
second := fixture.IssuePrefix + "-order-b"
|
||||
third := fixture.IssuePrefix + "-order-a"
|
||||
seedEdgeReaderIssues(t, ctx, fixture, first, second, third)
|
||||
|
||||
result := readEdges(t, ctx, fixture, publicops.EdgeReadRequest{IDs: []string{first, second, third}})
|
||||
assertEdgeReaderAnchorIDs(t, result, first, second, third)
|
||||
}
|
||||
|
||||
// RunEdgeReaderReportsAMissingAnchorRatherThanFailing pins
|
||||
// edgereader.go:45-48 and :188-191 together: a miss is reported ON THE ANCHOR
|
||||
// and the call still succeeds, so the anchors that were found still come back.
|
||||
//
|
||||
// The ghost is named BETWEEN two real anchors deliberately. A body that
|
||||
// short-circuited on the first miss would still return the first anchor, and a
|
||||
// case whose ghost came last would not tell the two apart.
|
||||
func RunEdgeReaderReportsAMissingAnchorRatherThanFailing(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
real1 := fixture.IssuePrefix + "-ghost-real1"
|
||||
real2 := fixture.IssuePrefix + "-ghost-real2"
|
||||
ghost := fixture.IssuePrefix + "-ghost-absent"
|
||||
seedEdgeReaderIssues(t, ctx, fixture, real1, real2)
|
||||
|
||||
result := readEdges(t, ctx, fixture, publicops.EdgeReadRequest{IDs: []string{real1, ghost, real2}})
|
||||
assertEdgeReaderAnchorIDs(t, result, real1, ghost, real2)
|
||||
assertEdgeReaderMissing(t, result, real1, false)
|
||||
assertEdgeReaderMissing(t, result, ghost, true)
|
||||
assertEdgeReaderMissing(t, result, real2, false)
|
||||
}
|
||||
|
||||
// RunEdgeReaderDistinguishesNoEdgesFromNoAnchor pins edgereader.go:104-115 —
|
||||
// the whole reason the flag exists. An issue with no dependencies is the COMMON
|
||||
// case, so a body that reported presence from "did any edges come back" would
|
||||
// pass every other case in this file and fail only here.
|
||||
func RunEdgeReaderDistinguishesNoEdgesFromNoAnchor(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
bare := fixture.IssuePrefix + "-bare-present"
|
||||
ghost := fixture.IssuePrefix + "-bare-absent"
|
||||
seedEdgeReaderIssues(t, ctx, fixture, bare)
|
||||
|
||||
result := readEdges(t, ctx, fixture, publicops.EdgeReadRequest{IDs: []string{bare, ghost}})
|
||||
assertEdgeReaderMissing(t, result, bare, false)
|
||||
assertEdgeReaderEdgeTargets(t, result, bare)
|
||||
assertEdgeReaderMissing(t, result, ghost, true)
|
||||
assertEdgeReaderEdgeTargets(t, result, ghost)
|
||||
|
||||
// Never nil, so a front door that marshals the answer emits [] rather than
|
||||
// null (edgereader.go:101-102).
|
||||
for _, anchor := range result.Anchors {
|
||||
if anchor.Edges == nil {
|
||||
t.Errorf("anchor %s has nil Edges; the contract promises an empty slice", anchor.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RunEdgeReaderReturnsTargetsVerbatim pins edgereader.go:12-17: an edge whose
|
||||
// target this database holds no row for is still an edge, returned with its
|
||||
// target spelled as stored.
|
||||
//
|
||||
// This is the sharpest difference from Relations, which drops such an edge
|
||||
// because it has no far end to hydrate. Two flavors are seeded — an
|
||||
// "external:" reference and a dangling id in another repository's prefix —
|
||||
// because they take different typed target columns and a body that read only
|
||||
// one of them would pass with the other.
|
||||
func RunEdgeReaderReturnsTargetsVerbatim(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
anchor := fixture.IssuePrefix + "-verbatim-src"
|
||||
external := "external:" + fixture.IssuePrefix + "-verbatim-ext"
|
||||
foreign := "zzforeign-" + fixture.IssuePrefix + "-verbatim"
|
||||
seedEdgeReaderIssues(t, ctx, fixture, anchor)
|
||||
seedEdgeReaderEdge(t, ctx, fixture, anchor, external, types.DepRelated)
|
||||
seedEdgeReaderEdge(t, ctx, fixture, anchor, foreign, types.DepRelated)
|
||||
|
||||
result := readEdges(t, ctx, fixture, publicops.EdgeReadRequest{IDs: []string{anchor}})
|
||||
assertEdgeReaderMissing(t, result, anchor, false)
|
||||
// Sorted by target id, and "external:..." sorts before "zzforeign-...".
|
||||
assertEdgeReaderEdgeTargets(t, result, anchor, external, foreign)
|
||||
}
|
||||
|
||||
// RunEdgeReaderCollapsesRepeatedAnchors pins edgereader.go:59-62: an id named
|
||||
// twice is one anchor, at the position of its first mention.
|
||||
//
|
||||
// The repeat is placed AFTER a different anchor, so a body that de-duplicated
|
||||
// by sorting rather than by first-mention order would answer b, a instead of a,
|
||||
// b and fail.
|
||||
func RunEdgeReaderCollapsesRepeatedAnchors(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
first := fixture.IssuePrefix + "-dup-b"
|
||||
second := fixture.IssuePrefix + "-dup-a"
|
||||
seedEdgeReaderIssues(t, ctx, fixture, first, second)
|
||||
|
||||
result := readEdges(t, ctx, fixture, publicops.EdgeReadRequest{
|
||||
IDs: []string{first, second, first, second, first},
|
||||
})
|
||||
assertEdgeReaderAnchorIDs(t, result, first, second)
|
||||
}
|
||||
|
||||
// RunEdgeReaderOrdersEdgesByTarget pins edgereader.go:87-99.
|
||||
//
|
||||
// The three edges are inserted in an order that is neither the target order nor
|
||||
// its reverse, so an implementation answering in insertion order fails here.
|
||||
//
|
||||
// ONLY THE PRIMARY KEY IS EXERCISED, and that is a property of the schema
|
||||
// rather than a hole in the case: all three backends refuse a second edge for a
|
||||
// (source, target) pair they already hold, so an answer with two edges to break
|
||||
// a tie between cannot be seeded through the fixture's AddDependency hook. The
|
||||
// leaf doc states the tiebreaker as a totality guarantee for that reason.
|
||||
func RunEdgeReaderOrdersEdgesByTarget(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
anchor := fixture.IssuePrefix + "-sort-src"
|
||||
late := fixture.IssuePrefix + "-sort-z"
|
||||
middle := fixture.IssuePrefix + "-sort-m"
|
||||
early := fixture.IssuePrefix + "-sort-a"
|
||||
seedEdgeReaderIssues(t, ctx, fixture, anchor, late, middle, early)
|
||||
seedEdgeReaderEdge(t, ctx, fixture, anchor, middle, types.DepRelated)
|
||||
seedEdgeReaderEdge(t, ctx, fixture, anchor, late, types.DepRelated)
|
||||
seedEdgeReaderEdge(t, ctx, fixture, anchor, early, types.DepBlocks)
|
||||
|
||||
result := readEdges(t, ctx, fixture, publicops.EdgeReadRequest{IDs: []string{anchor}})
|
||||
assertEdgeReaderEdgeTargets(t, result, anchor, early, middle, late)
|
||||
|
||||
// The surrogate key is empty on every row here, which is why it is NOT a
|
||||
// third sort term (edgereader.go:19-23).
|
||||
for _, edge := range edgeReaderAnchor(t, result, anchor).Edges {
|
||||
if edge.ID != "" {
|
||||
t.Errorf("edge %s -> %s carries ID %q; the source-keyed read does not select it and the contract says it is empty",
|
||||
edge.IssueID, edge.DependsOnID, edge.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RunEdgeReaderFiltersEdgesNotAnchors pins edgereader.go:73-75: the type filter
|
||||
// narrows edges, and an anchor whose every edge it rejects stays present with
|
||||
// none.
|
||||
//
|
||||
// That anchor is the case worth having. A body that dropped an anchor with no
|
||||
// surviving edges would look correct on the first half of this assertion and
|
||||
// would turn a filtered listing into a report that the issue does not exist.
|
||||
func RunEdgeReaderFiltersEdgesNotAnchors(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
kept := fixture.IssuePrefix + "-filter-kept"
|
||||
dropped := fixture.IssuePrefix + "-filter-dropped"
|
||||
blocker := fixture.IssuePrefix + "-filter-blocker"
|
||||
related := fixture.IssuePrefix + "-filter-related"
|
||||
seedEdgeReaderIssues(t, ctx, fixture, kept, dropped, blocker, related)
|
||||
seedEdgeReaderEdge(t, ctx, fixture, kept, blocker, types.DepBlocks)
|
||||
seedEdgeReaderEdge(t, ctx, fixture, kept, related, types.DepRelated)
|
||||
seedEdgeReaderEdge(t, ctx, fixture, dropped, related, types.DepRelated)
|
||||
|
||||
result := readEdges(t, ctx, fixture, publicops.EdgeReadRequest{
|
||||
IDs: []string{kept, dropped},
|
||||
Types: []types.DependencyType{types.DepBlocks},
|
||||
})
|
||||
assertEdgeReaderAnchorIDs(t, result, kept, dropped)
|
||||
assertEdgeReaderEdgeTargets(t, result, kept, blocker)
|
||||
assertEdgeReaderMissing(t, result, dropped, false)
|
||||
assertEdgeReaderEdgeTargets(t, result, dropped)
|
||||
}
|
||||
|
||||
// RunEdgeReaderReadsBothPlanes pins the anchor probe against edgereader.go:104:
|
||||
// "no issue AND no wisp carries this id". A wisp anchor is present, and its
|
||||
// edges come back from the ephemeral tier the seed routed them to.
|
||||
//
|
||||
// It is the case most likely to catch a real divergence, because the three
|
||||
// bodies reach the two planes by different routes: a batched EXISTS over
|
||||
// `issues` then `wisps` on the store side, and GetIssuesByIDs plus
|
||||
// GetWispsByIDs on the unit-of-work side.
|
||||
func RunEdgeReaderReadsBothPlanes(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
wisp := fixture.IssuePrefix + "-plane-wisp"
|
||||
target := fixture.IssuePrefix + "-plane-target"
|
||||
seedEdgeReaderIssues(t, ctx, fixture, target)
|
||||
seedEdgeReaderWisp(t, ctx, fixture, wisp)
|
||||
seedEdgeReaderEdge(t, ctx, fixture, wisp, target, types.DepBlocks)
|
||||
|
||||
result := readEdges(t, ctx, fixture, publicops.EdgeReadRequest{IDs: []string{wisp}})
|
||||
assertEdgeReaderMissing(t, result, wisp, false)
|
||||
assertEdgeReaderEdgeTargets(t, result, wisp, target)
|
||||
}
|
||||
|
||||
// RunEdgeReaderResolvesExactIDsOnly pins edgereader.go:36-43: a prefix of a
|
||||
// real id, a case variant and an id carrying whitespace are all misses, not
|
||||
// resolutions.
|
||||
//
|
||||
// They are misses rather than errors here, which is the per-anchor spelling of
|
||||
// the same promise RelatedRequest.ID makes: this role reports them beside the
|
||||
// anchor that did resolve.
|
||||
func RunEdgeReaderResolvesExactIDsOnly(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
anchor := fixture.IssuePrefix + "-exact-anchor"
|
||||
target := fixture.IssuePrefix + "-exact-target"
|
||||
seedEdgeReaderIssues(t, ctx, fixture, anchor, target)
|
||||
seedEdgeReaderEdge(t, ctx, fixture, anchor, target, types.DepBlocks)
|
||||
|
||||
prefix := anchor[:len(anchor)-2]
|
||||
spaced := " " + anchor + " "
|
||||
result := readEdges(t, ctx, fixture, publicops.EdgeReadRequest{
|
||||
IDs: []string{anchor, prefix, spaced},
|
||||
})
|
||||
assertEdgeReaderAnchorIDs(t, result, anchor, prefix, spaced)
|
||||
assertEdgeReaderMissing(t, result, anchor, false)
|
||||
assertEdgeReaderMissing(t, result, prefix, true)
|
||||
assertEdgeReaderMissing(t, result, spaced, true)
|
||||
}
|
||||
|
||||
// RunEdgeReaderAnswersAnEmptyRequest pins edgereader.go:54-57: no anchors is
|
||||
// not an error, it is an answer with no anchors.
|
||||
func RunEdgeReaderAnswersAnEmptyRequest(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
result, err := fixture.EdgeReader.ReadEdges(ctx, publicops.EdgeReadRequest{})
|
||||
if err != nil {
|
||||
t.Fatalf("ReadEdges with no ids = %v, want an empty answer", err)
|
||||
}
|
||||
if len(result.Anchors) != 0 {
|
||||
t.Fatalf("ReadEdges with no ids returned %d anchors, want none", len(result.Anchors))
|
||||
}
|
||||
if result.Anchors == nil {
|
||||
t.Error("Anchors is nil; the contract promises it is never nil for a successful call")
|
||||
}
|
||||
}
|
||||
|
||||
// RunEdgeReaderRefusesAnEmptyID pins edgereader.go:50-52: the empty string is
|
||||
// ErrValidation rather than a nameless ghost.
|
||||
//
|
||||
// The refusal must beat the good anchor beside it — a body that answered for
|
||||
// the ids it could and reported the empty one as missing would leave a caller
|
||||
// with an anchor it has no name for.
|
||||
func RunEdgeReaderRefusesAnEmptyID(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
anchor := fixture.IssuePrefix + "-emptyid-anchor"
|
||||
seedEdgeReaderIssues(t, ctx, fixture, anchor)
|
||||
|
||||
_, err := fixture.EdgeReader.ReadEdges(ctx, publicops.EdgeReadRequest{IDs: []string{anchor, ""}})
|
||||
if !errors.Is(err, publicops.ErrValidation) {
|
||||
t.Fatalf("ReadEdges with an empty id = %v, want ErrValidation", err)
|
||||
}
|
||||
}
|
||||
|
||||
// RunEdgeReaderRefusesAnUnusableType pins edgereader.go:67-71: an entry no edge
|
||||
// could ever carry is ErrValidation rather than a filter that matches nothing.
|
||||
//
|
||||
// The vocabulary itself stays OPEN, which the second half asserts: a
|
||||
// workspace's own type is accepted and simply matches no edge here.
|
||||
func RunEdgeReaderRefusesAnUnusableType(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
anchor := fixture.IssuePrefix + "-badtype-anchor"
|
||||
target := fixture.IssuePrefix + "-badtype-target"
|
||||
seedEdgeReaderIssues(t, ctx, fixture, anchor, target)
|
||||
seedEdgeReaderEdge(t, ctx, fixture, anchor, target, types.DepBlocks)
|
||||
|
||||
_, err := fixture.EdgeReader.ReadEdges(ctx, publicops.EdgeReadRequest{
|
||||
IDs: []string{anchor},
|
||||
Types: []types.DependencyType{""},
|
||||
})
|
||||
if !errors.Is(err, publicops.ErrValidation) {
|
||||
t.Fatalf("ReadEdges with an empty dependency type = %v, want ErrValidation", err)
|
||||
}
|
||||
|
||||
result := readEdges(t, ctx, fixture, publicops.EdgeReadRequest{
|
||||
IDs: []string{anchor},
|
||||
Types: []types.DependencyType{"workspace-invented-type"},
|
||||
})
|
||||
assertEdgeReaderMissing(t, result, anchor, false)
|
||||
assertEdgeReaderEdgeTargets(t, result, anchor)
|
||||
}
|
||||
|
||||
// RunEdgeReaderLeavesTheRequestAlone pins the no-mutation clause at
|
||||
// edgereader.go:169-173. IDs and Types are the two members a body could write
|
||||
// through to the caller, and de-duplication and filtering are exactly the steps
|
||||
// that would.
|
||||
func RunEdgeReaderLeavesTheRequestAlone(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
anchor := fixture.IssuePrefix + "-immutable-anchor"
|
||||
target := fixture.IssuePrefix + "-immutable-target"
|
||||
seedEdgeReaderIssues(t, ctx, fixture, anchor, target)
|
||||
seedEdgeReaderEdge(t, ctx, fixture, anchor, target, types.DepBlocks)
|
||||
|
||||
ids := []string{anchor, anchor, target}
|
||||
depTypes := []types.DependencyType{types.DepRelated, types.DepBlocks}
|
||||
readEdges(t, ctx, fixture, publicops.EdgeReadRequest{IDs: ids, Types: depTypes})
|
||||
|
||||
if len(ids) != 3 || ids[0] != anchor || ids[1] != anchor || ids[2] != target {
|
||||
t.Errorf("the request's IDs slice is now %v; the contract says a body de-duplicates into its own copy", ids)
|
||||
}
|
||||
if len(depTypes) != 2 || depTypes[0] != types.DepRelated || depTypes[1] != types.DepBlocks {
|
||||
t.Errorf("the request's Types slice is now %v; the contract says a body reads it without reordering it", depTypes)
|
||||
}
|
||||
}
|
||||
|
||||
// RunEdgeReaderWritesNothing pins edgereader.go:175-178: reading edges records
|
||||
// no history entry.
|
||||
//
|
||||
// The delta is taken around the call rather than as an absolute count, because
|
||||
// the seeds above it are versioned writes of their own.
|
||||
func RunEdgeReaderWritesNothing(t *testing.T, ctx context.Context, fixture EdgeReaderFixture) {
|
||||
t.Helper()
|
||||
if fixture.CountHistory == nil {
|
||||
t.Skip("this backend cannot observe history, so the writes-nothing clause cannot be checked here")
|
||||
}
|
||||
anchor := fixture.IssuePrefix + "-quiet-anchor"
|
||||
target := fixture.IssuePrefix + "-quiet-target"
|
||||
ghost := fixture.IssuePrefix + "-quiet-ghost"
|
||||
seedEdgeReaderIssues(t, ctx, fixture, anchor, target)
|
||||
seedEdgeReaderEdge(t, ctx, fixture, anchor, target, types.DepBlocks)
|
||||
|
||||
before, err := fixture.CountHistory(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("CountHistory before: %v", err)
|
||||
}
|
||||
readEdges(t, ctx, fixture, publicops.EdgeReadRequest{IDs: []string{anchor, ghost}})
|
||||
// A refusal changes nothing either, so the same delta covers both.
|
||||
_, _ = fixture.EdgeReader.ReadEdges(ctx, publicops.EdgeReadRequest{IDs: []string{""}})
|
||||
after, err := fixture.CountHistory(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("CountHistory after: %v", err)
|
||||
}
|
||||
if after != before {
|
||||
t.Fatalf("history entries went %d -> %d across two edge reads, want no change", before, after)
|
||||
}
|
||||
}
|
||||
|
||||
func readEdges(t *testing.T, ctx context.Context, fixture EdgeReaderFixture, request publicops.EdgeReadRequest) publicops.EdgeReadResult {
|
||||
t.Helper()
|
||||
result, err := fixture.EdgeReader.ReadEdges(ctx, request)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadEdges(%v): %v", request.IDs, err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func seedEdgeReaderIssues(t *testing.T, ctx context.Context, fixture EdgeReaderFixture, ids ...string) {
|
||||
t.Helper()
|
||||
for _, id := range ids {
|
||||
if err := fixture.CreateIssue(ctx, edgeReaderSeed(id, false), "edge-reader-seed"); err != nil {
|
||||
t.Fatalf("seed issue %s: %v", id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func seedEdgeReaderWisp(t *testing.T, ctx context.Context, fixture EdgeReaderFixture, id string) {
|
||||
t.Helper()
|
||||
if err := fixture.CreateWisp(ctx, edgeReaderSeed(id, true), "edge-reader-seed"); err != nil {
|
||||
t.Fatalf("seed wisp %s: %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
func seedEdgeReaderEdge(t *testing.T, ctx context.Context, fixture EdgeReaderFixture, from, to string, depType types.DependencyType) {
|
||||
t.Helper()
|
||||
if err := fixture.AddDependency(ctx, &types.Dependency{
|
||||
IssueID: from, DependsOnID: to, Type: depType,
|
||||
}, "edge-reader-seed"); err != nil {
|
||||
t.Fatalf("seed edge %s -> %s (%s): %v", from, to, depType, err)
|
||||
}
|
||||
}
|
||||
|
||||
func edgeReaderSeed(id string, ephemeral bool) *types.Issue {
|
||||
return &types.Issue{
|
||||
ID: id,
|
||||
Title: id,
|
||||
Status: types.StatusOpen,
|
||||
Priority: 2,
|
||||
IssueType: types.TypeTask,
|
||||
Ephemeral: ephemeral,
|
||||
}
|
||||
}
|
||||
|
||||
func edgeReaderAnchor(t *testing.T, result publicops.EdgeReadResult, id string) publicops.AnchorEdges {
|
||||
t.Helper()
|
||||
for _, anchor := range result.Anchors {
|
||||
if anchor.ID == id {
|
||||
return anchor
|
||||
}
|
||||
}
|
||||
t.Fatalf("no anchor %q in the answer; got %v", id, edgeReaderAnchorIDs(result))
|
||||
return publicops.AnchorEdges{}
|
||||
}
|
||||
|
||||
func edgeReaderAnchorIDs(result publicops.EdgeReadResult) []string {
|
||||
out := make([]string, 0, len(result.Anchors))
|
||||
for _, anchor := range result.Anchors {
|
||||
out = append(out, anchor.ID)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func assertEdgeReaderAnchorIDs(t *testing.T, result publicops.EdgeReadResult, want ...string) {
|
||||
t.Helper()
|
||||
got := edgeReaderAnchorIDs(result)
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("anchors = %v, want %v", got, want)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("anchors = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertEdgeReaderMissing(t *testing.T, result publicops.EdgeReadResult, id string, want bool) {
|
||||
t.Helper()
|
||||
if got := edgeReaderAnchor(t, result, id).Missing; got != want {
|
||||
t.Errorf("anchor %s Missing = %t, want %t", id, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// assertEdgeReaderEdgeTargets compares the anchor's edge targets IN ORDER, so
|
||||
// one helper serves both the "which edges" and the "in what order" assertions.
|
||||
func assertEdgeReaderEdgeTargets(t *testing.T, result publicops.EdgeReadResult, id string, want ...string) {
|
||||
t.Helper()
|
||||
edges := edgeReaderAnchor(t, result, id).Edges
|
||||
got := make([]string, 0, len(edges))
|
||||
for _, edge := range edges {
|
||||
if edge.IssueID != id {
|
||||
t.Errorf("anchor %s carries an edge whose source is %s; the answer is keyed by source", id, edge.IssueID)
|
||||
}
|
||||
got = append(got, edge.DependsOnID)
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("anchor %s edge targets = %v, want %v", id, got, want)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("anchor %s edge targets = %v, want %v", id, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
175
cmd/bd/dep.go
175
cmd/bd/dep.go
|
|
@ -688,6 +688,106 @@ func dependencyStoreKey(s storage.DoltStorage) string {
|
|||
return fmt.Sprintf("instance:%p", s)
|
||||
}
|
||||
|
||||
// depListAnchor is one resolved `bd dep list` argument: the canonical id, the
|
||||
// store that actually holds it, and the routing handle that has to be closed.
|
||||
type depListAnchor struct {
|
||||
fullID string
|
||||
store storage.DoltStorage
|
||||
result *RoutedResult
|
||||
}
|
||||
|
||||
// readDepListEdges asks each anchor's OWN store for its stored edges and
|
||||
// reassembles the answers into the order the arguments named.
|
||||
//
|
||||
// The grouping is what keeps the answer on ONE shape. Before the role, a batch
|
||||
// whose anchors routed to different stores — and a batch whose single batched
|
||||
// read simply failed — fell through to the hydrated neighbor listing, so
|
||||
// `bd dep list a b c --json` silently emitted an array of ISSUES where it
|
||||
// documents an array of dependency records. Both fall-throughs are gone: a
|
||||
// failure is now a failure, and a split batch is N role calls merged back into
|
||||
// one answer.
|
||||
func readDepListEdges(ctx context.Context, anchors []depListAnchor, typeFilter string) ([]issueops.AnchorEdges, error) {
|
||||
var depTypes []types.DependencyType
|
||||
if typeFilter != "" {
|
||||
depTypes = []types.DependencyType{types.DependencyType(typeFilter)}
|
||||
}
|
||||
|
||||
// Grouped by store IDENTITY, not by the store's workspace path: two handles
|
||||
// onto the same database are still two connections, and asking one of them
|
||||
// for the other's ids would answer that every one of them is missing.
|
||||
byStore := map[storage.DoltStorage][]string{}
|
||||
var order []storage.DoltStorage
|
||||
for _, anchor := range anchors {
|
||||
if _, seen := byStore[anchor.store]; !seen {
|
||||
order = append(order, anchor.store)
|
||||
}
|
||||
byStore[anchor.store] = append(byStore[anchor.store], anchor.fullID)
|
||||
}
|
||||
|
||||
answered := make(map[string]issueops.AnchorEdges, len(anchors))
|
||||
for _, st := range order {
|
||||
reader, err := st.EdgeReader()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := reader.ReadEdges(ctx, issueops.EdgeReadRequest{IDs: byStore[st], Types: depTypes})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, anchor := range result.Anchors {
|
||||
answered[anchor.ID] = anchor
|
||||
}
|
||||
}
|
||||
|
||||
out := make([]issueops.AnchorEdges, 0, len(anchors))
|
||||
seen := make(map[string]struct{}, len(anchors))
|
||||
for _, anchor := range anchors {
|
||||
if _, dup := seen[anchor.fullID]; dup {
|
||||
continue
|
||||
}
|
||||
seen[anchor.fullID] = struct{}{}
|
||||
out = append(out, answered[anchor.fullID])
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// printDepListEdges renders the role's per-anchor answer, and is shared by both
|
||||
// routes so the two cannot drift apart in what they print.
|
||||
//
|
||||
// A GHOST ANCHOR goes to stderr in both modes, in the same words the direct
|
||||
// route already uses for an argument that would not resolve. Keeping it off
|
||||
// stdout is what leaves `--json` a flat array of dependency records, which is
|
||||
// the shape the command documents.
|
||||
func printDepListEdges(anchors []issueops.AnchorEdges) error {
|
||||
for _, anchor := range anchors {
|
||||
if anchor.Missing {
|
||||
fmt.Fprintf(os.Stderr, "warning: no issue found: %s (skipped)\n", anchor.ID)
|
||||
}
|
||||
}
|
||||
if jsonOutput {
|
||||
out := []*types.Dependency{}
|
||||
for _, anchor := range anchors {
|
||||
out = append(out, anchor.Edges...)
|
||||
}
|
||||
return outputJSON(out)
|
||||
}
|
||||
for _, anchor := range anchors {
|
||||
if anchor.Missing {
|
||||
continue
|
||||
}
|
||||
if len(anchor.Edges) == 0 {
|
||||
fmt.Printf("\n%s has no dependencies\n", anchor.ID)
|
||||
continue
|
||||
}
|
||||
fmt.Printf("\n%s %s depends on:\n\n", ui.RenderAccent("📋"), anchor.ID)
|
||||
for _, dep := range anchor.Edges {
|
||||
fmt.Printf(" %s via %s\n", dep.DependsOnID, dep.Type)
|
||||
}
|
||||
}
|
||||
fmt.Println()
|
||||
return nil
|
||||
}
|
||||
|
||||
var depListCmd = &cobra.Command{
|
||||
Use: "list [issue-id...]",
|
||||
Short: "List dependencies or dependents of one or more issues",
|
||||
|
|
@ -729,12 +829,7 @@ Examples:
|
|||
direction = "down"
|
||||
}
|
||||
|
||||
type resolvedID struct {
|
||||
fullID string
|
||||
store storage.DoltStorage
|
||||
result *RoutedResult
|
||||
}
|
||||
var resolved []resolvedID
|
||||
var resolved []depListAnchor
|
||||
batchMode := len(args) > 1
|
||||
for _, arg := range args {
|
||||
routedResult, err := resolveAndGetIssueWithRouting(ctx, store, arg)
|
||||
|
|
@ -756,7 +851,7 @@ Examples:
|
|||
if routedResult.Routed && routedResult.Store != nil {
|
||||
depStore = routedResult.Store
|
||||
}
|
||||
resolved = append(resolved, resolvedID{
|
||||
resolved = append(resolved, depListAnchor{
|
||||
fullID: routedResult.ResolvedID,
|
||||
store: depStore,
|
||||
result: routedResult,
|
||||
|
|
@ -777,60 +872,22 @@ Examples:
|
|||
}
|
||||
}()
|
||||
|
||||
// The multi-id edge listing is a different question with a different
|
||||
// answer shape — raw edge records keyed by source, printed per source —
|
||||
// and no role describes it: Relations is anchored on ONE issue and
|
||||
// answers with the issues on the far end of its edges, not with the
|
||||
// edges themselves. It keeps the batched records read, exactly as the
|
||||
// proxied route keeps its own unit of work for the same question.
|
||||
// The multi-id edge listing is a different question from the neighbor
|
||||
// query below — raw edge records keyed by source, printed per source,
|
||||
// with a per-anchor miss — and it is on the EdgeReader role. Relations
|
||||
// cannot answer it: it is anchored on ONE issue, it answers with the
|
||||
// issues on the far end of its edges rather than the edges themselves,
|
||||
// and it drops every edge whose target this database has no row for.
|
||||
//
|
||||
// The accessor is taken PER STORE rather than once for the command,
|
||||
// like the neighbor query below: a routed anchor answers from its own
|
||||
// store, carrying its own decorator stack.
|
||||
if len(resolved) > 1 && direction == "down" {
|
||||
allSameStore := true
|
||||
firstStore := resolved[0].store
|
||||
for _, r := range resolved[1:] {
|
||||
if r.store != firstStore {
|
||||
allSameStore = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if allSameStore {
|
||||
ids := make([]string, len(resolved))
|
||||
for i, r := range resolved {
|
||||
ids[i] = r.fullID
|
||||
}
|
||||
depMap, err := firstStore.GetDependencyRecordsForIssues(ctx, ids)
|
||||
if err == nil {
|
||||
var allDeps []*types.Dependency
|
||||
for _, id := range ids {
|
||||
for _, dep := range depMap[id] {
|
||||
if typeFilter == "" || string(dep.Type) == typeFilter {
|
||||
allDeps = append(allDeps, dep)
|
||||
}
|
||||
}
|
||||
}
|
||||
if jsonOutput {
|
||||
if allDeps == nil {
|
||||
allDeps = []*types.Dependency{}
|
||||
}
|
||||
return outputJSON(allDeps)
|
||||
}
|
||||
for _, id := range ids {
|
||||
deps := depMap[id]
|
||||
if len(deps) == 0 {
|
||||
fmt.Printf("\n%s has no dependencies\n", id)
|
||||
continue
|
||||
}
|
||||
fmt.Printf("\n%s %s depends on:\n\n", ui.RenderAccent("📋"), id)
|
||||
for _, dep := range deps {
|
||||
if typeFilter != "" && string(dep.Type) != typeFilter {
|
||||
continue
|
||||
}
|
||||
fmt.Printf(" %s via %s\n", dep.DependsOnID, dep.Type)
|
||||
}
|
||||
}
|
||||
fmt.Println()
|
||||
return nil
|
||||
}
|
||||
anchors, err := readDepListEdges(ctx, resolved, typeFilter)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
return printDepListEdges(anchors)
|
||||
}
|
||||
|
||||
// The neighbor query is on the Relations role: one call per anchor, each
|
||||
|
|
|
|||
253
cmd/bd/dep_edge_reader_test.go
Normal file
253
cmd/bd/dep_edge_reader_test.go
Normal file
|
|
@ -0,0 +1,253 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// These cover `bd dep list a b c`'s two halves above the role: which store each
|
||||
// resolved anchor is asked, and what the shared printer emits. Everything below
|
||||
// them — what Missing means, the edge order, the type filter — is the role's,
|
||||
// and is pinned by backend/conformance/edge_reader_contract.go at all three
|
||||
// backends.
|
||||
|
||||
// edgeReaderStore is a DoltStorage whose only real method is the accessor under
|
||||
// test. Every other call is a nil panic, which is the assertion: this path must
|
||||
// reach storage through the role and nothing else.
|
||||
type edgeReaderStore struct {
|
||||
storage.DoltStorage
|
||||
reader issueops.EdgeReader
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *edgeReaderStore) EdgeReader() (issueops.EdgeReader, error) {
|
||||
if s.err != nil {
|
||||
return nil, s.err
|
||||
}
|
||||
return s.reader, nil
|
||||
}
|
||||
|
||||
type fakeEdgeReader struct {
|
||||
edges map[string][]*types.Dependency
|
||||
missing map[string]bool
|
||||
err error
|
||||
|
||||
mu sync.Mutex
|
||||
calls [][]string
|
||||
}
|
||||
|
||||
func (f *fakeEdgeReader) ReadEdges(_ context.Context, req issueops.EdgeReadRequest) (issueops.EdgeReadResult, error) {
|
||||
f.mu.Lock()
|
||||
f.calls = append(f.calls, append([]string(nil), req.IDs...))
|
||||
f.mu.Unlock()
|
||||
if f.err != nil {
|
||||
return issueops.EdgeReadResult{}, f.err
|
||||
}
|
||||
result := issueops.EdgeReadResult{Anchors: make([]issueops.AnchorEdges, 0, len(req.IDs))}
|
||||
for _, id := range req.IDs {
|
||||
result.Anchors = append(result.Anchors, issueops.AnchorEdges{
|
||||
ID: id,
|
||||
Edges: f.edges[id],
|
||||
Missing: f.missing[id],
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func edgeReaderAnchorFor(id string, reader issueops.EdgeReader) depListAnchor {
|
||||
return depListAnchor{fullID: id, store: &edgeReaderStore{reader: reader}}
|
||||
}
|
||||
|
||||
// TestDepListEdgesReportsTheReadFailure is the regression for the shipped
|
||||
// defect this role's adoption fixes.
|
||||
//
|
||||
// The pre-role code called GetDependencyRecordsForIssues and, on ANY error,
|
||||
// fell through to the hydrated neighbor listing — so a transient failure
|
||||
// turned `bd dep list a b --json` from an array of dependency records into an
|
||||
// array of ISSUES, with no error and no warning. A caller parsing the first
|
||||
// shape read an empty result from the second.
|
||||
func TestDepListEdgesReportsTheReadFailure(t *testing.T) {
|
||||
want := errors.New("dependency table is unreachable")
|
||||
reader := &fakeEdgeReader{err: want}
|
||||
anchors := []depListAnchor{
|
||||
edgeReaderAnchorFor("bd-1", reader),
|
||||
edgeReaderAnchorFor("bd-2", reader),
|
||||
}
|
||||
|
||||
if _, err := readDepListEdges(context.Background(), anchors, ""); !errors.Is(err, want) {
|
||||
t.Fatalf("readDepListEdges error = %v, want the read failure; a fall-through here changes the --json shape", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDepListEdgesAsksEachAnchorsOwnStore pins the routed case, which is the
|
||||
// second half of the same defect: a batch whose anchors resolved to different
|
||||
// stores also fell through to the neighbor listing, so a cross-rig
|
||||
// `bd dep list` emitted a different document from a same-rig one.
|
||||
//
|
||||
// It also pins that no store is asked for another store's ids — an id sent to
|
||||
// the wrong database would come back Missing, which reads as "no such issue".
|
||||
func TestDepListEdgesAsksEachAnchorsOwnStore(t *testing.T) {
|
||||
home := &fakeEdgeReader{edges: map[string][]*types.Dependency{
|
||||
"hq-1": {{IssueID: "hq-1", DependsOnID: "hq-2", Type: types.DepBlocks}},
|
||||
}}
|
||||
rig := &fakeEdgeReader{edges: map[string][]*types.Dependency{
|
||||
"gt-1": {{IssueID: "gt-1", DependsOnID: "gt-2", Type: types.DepRelated}},
|
||||
}}
|
||||
homeStore := &edgeReaderStore{reader: home}
|
||||
rigStore := &edgeReaderStore{reader: rig}
|
||||
|
||||
anchors := []depListAnchor{
|
||||
{fullID: "hq-1", store: homeStore},
|
||||
{fullID: "gt-1", store: rigStore},
|
||||
{fullID: "hq-3", store: homeStore},
|
||||
}
|
||||
got, err := readDepListEdges(context.Background(), anchors, "")
|
||||
if err != nil {
|
||||
t.Fatalf("readDepListEdges: %v", err)
|
||||
}
|
||||
|
||||
// The answer is in ARGUMENT order, not store order: the two stores were
|
||||
// called one after the other, and reassembling by store would have put
|
||||
// gt-1 last.
|
||||
wantOrder := []string{"hq-1", "gt-1", "hq-3"}
|
||||
if len(got) != len(wantOrder) {
|
||||
t.Fatalf("anchors = %d, want %d", len(got), len(wantOrder))
|
||||
}
|
||||
for i, want := range wantOrder {
|
||||
if got[i].ID != want {
|
||||
t.Fatalf("anchor order = %v, want %v", []string{got[0].ID, got[1].ID, got[2].ID}, wantOrder)
|
||||
}
|
||||
}
|
||||
|
||||
// One call per store, each carrying only its own ids.
|
||||
if len(home.calls) != 1 || strings.Join(home.calls[0], ",") != "hq-1,hq-3" {
|
||||
t.Errorf("home store calls = %v, want one for [hq-1 hq-3]", home.calls)
|
||||
}
|
||||
if len(rig.calls) != 1 || strings.Join(rig.calls[0], ",") != "gt-1" {
|
||||
t.Errorf("rig store calls = %v, want one for [gt-1]", rig.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDepListEdgesCollapsesARepeatedAnchor pins that a repeat is one entry, so
|
||||
// the printed answer and the --json array cannot double-count an id the caller
|
||||
// named twice.
|
||||
func TestDepListEdgesCollapsesARepeatedAnchor(t *testing.T) {
|
||||
reader := &fakeEdgeReader{edges: map[string][]*types.Dependency{
|
||||
"bd-1": {{IssueID: "bd-1", DependsOnID: "bd-2", Type: types.DepBlocks}},
|
||||
}}
|
||||
store := &edgeReaderStore{reader: reader}
|
||||
anchors := []depListAnchor{
|
||||
{fullID: "bd-1", store: store},
|
||||
{fullID: "bd-9", store: store},
|
||||
{fullID: "bd-1", store: store},
|
||||
}
|
||||
|
||||
got, err := readDepListEdges(context.Background(), anchors, "")
|
||||
if err != nil {
|
||||
t.Fatalf("readDepListEdges: %v", err)
|
||||
}
|
||||
if len(got) != 2 || got[0].ID != "bd-1" || got[1].ID != "bd-9" {
|
||||
t.Fatalf("anchors = %+v, want bd-1 then bd-9, each once", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDepListEdgesForwardsTheTypeFilter pins that --type reaches the role
|
||||
// rather than being applied after the read. The role narrows in the query it
|
||||
// runs; a filter applied here would have read every edge first.
|
||||
func TestDepListEdgesForwardsTheTypeFilter(t *testing.T) {
|
||||
reader := &recordingTypeEdgeReader{}
|
||||
anchors := []depListAnchor{
|
||||
edgeReaderAnchorFor("bd-1", reader),
|
||||
edgeReaderAnchorFor("bd-2", reader),
|
||||
}
|
||||
if _, err := readDepListEdges(context.Background(), anchors, "tracks"); err != nil {
|
||||
t.Fatalf("readDepListEdges: %v", err)
|
||||
}
|
||||
if len(reader.types) != 1 || reader.types[0] != types.DependencyType("tracks") {
|
||||
t.Fatalf("role was handed types %v, want the one --type named", reader.types)
|
||||
}
|
||||
}
|
||||
|
||||
type recordingTypeEdgeReader struct{ types []types.DependencyType }
|
||||
|
||||
func (r *recordingTypeEdgeReader) ReadEdges(_ context.Context, req issueops.EdgeReadRequest) (issueops.EdgeReadResult, error) {
|
||||
r.types = append([]types.DependencyType(nil), req.Types...)
|
||||
return issueops.EdgeReadResult{Anchors: []issueops.AnchorEdges{}}, nil
|
||||
}
|
||||
|
||||
// TestDepListPrintsGhostAnchorsToStderr pins the Q11-approved user-visible
|
||||
// change, and the reason it is on stderr.
|
||||
//
|
||||
// A ghost used to print "<id> has no dependencies" on the proxied route, which
|
||||
// reads as a clean graph. It now prints the warning the direct route has always
|
||||
// printed for an argument it could not resolve. Keeping it off stdout is what
|
||||
// leaves --json a flat array of dependency records.
|
||||
func TestDepListPrintsGhostAnchorsToStderr(t *testing.T) {
|
||||
anchors := []issueops.AnchorEdges{
|
||||
{ID: "bd-1", Edges: []*types.Dependency{{IssueID: "bd-1", DependsOnID: "bd-2", Type: types.DepBlocks}}},
|
||||
{ID: "bd-ghost", Missing: true},
|
||||
{ID: "bd-bare"},
|
||||
}
|
||||
|
||||
t.Run("human", func(t *testing.T) {
|
||||
stdout, stderr := captureDepListOutput(t, false, anchors)
|
||||
if !strings.Contains(stderr, "warning: no issue found: bd-ghost (skipped)") {
|
||||
t.Errorf("stderr = %q, want the ghost warning", stderr)
|
||||
}
|
||||
if strings.Contains(stdout, "bd-ghost") {
|
||||
t.Errorf("stdout = %q, want the ghost anchor absent from the listing", stdout)
|
||||
}
|
||||
if !strings.Contains(stdout, "bd-bare has no dependencies") {
|
||||
t.Errorf("stdout = %q, want the present-but-edgeless anchor reported as having none", stdout)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("json", func(t *testing.T) {
|
||||
stdout, stderr := captureDepListOutput(t, true, anchors)
|
||||
if !strings.Contains(stderr, "warning: no issue found: bd-ghost (skipped)") {
|
||||
t.Errorf("stderr = %q, want the ghost warning in --json mode too", stderr)
|
||||
}
|
||||
var got []*types.Dependency
|
||||
if err := json.Unmarshal([]byte(stdout), &got); err != nil {
|
||||
t.Fatalf("--json output %q is not an array of dependency records: %v", stdout, err)
|
||||
}
|
||||
if len(got) != 1 || got[0].DependsOnID != "bd-2" {
|
||||
t.Fatalf("--json output = %q, want the one edge flattened across the anchors", stdout)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func captureDepListOutput(t *testing.T, asJSON bool, anchors []issueops.AnchorEdges) (stdout, stderr string) {
|
||||
t.Helper()
|
||||
outR, outW, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatalf("pipe: %v", err)
|
||||
}
|
||||
errR, errW, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatalf("pipe: %v", err)
|
||||
}
|
||||
oldOut, oldErr, oldJSON := os.Stdout, os.Stderr, jsonOutput
|
||||
os.Stdout, os.Stderr, jsonOutput = outW, errW, asJSON
|
||||
t.Cleanup(func() { os.Stdout, os.Stderr, jsonOutput = oldOut, oldErr, oldJSON })
|
||||
|
||||
printErr := printDepListEdges(anchors)
|
||||
_ = outW.Close()
|
||||
_ = errW.Close()
|
||||
outBytes, _ := io.ReadAll(outR)
|
||||
errBytes, _ := io.ReadAll(errR)
|
||||
if printErr != nil {
|
||||
t.Fatalf("printDepListEdges: %v", printErr)
|
||||
}
|
||||
return string(outBytes), string(errBytes)
|
||||
}
|
||||
|
|
@ -51,6 +51,20 @@ func proxiedIssueRelations() (issueops.Relations, error) {
|
|||
return src.IssueRelations()
|
||||
}
|
||||
|
||||
// proxiedEdgeReader hands back the guarded stored-edge surface for the
|
||||
// proxied-server provider, through the provider's OWN capability accessor —
|
||||
// the same two-step a direct command performs on a store.
|
||||
func proxiedEdgeReader() (issueops.EdgeReader, error) {
|
||||
if uowProvider == nil {
|
||||
return nil, errors.New("proxied-server UOW provider not initialized")
|
||||
}
|
||||
src, ok := uowProvider.(uow.EdgeReaderSource)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("proxied-server provider %T does not offer the stored-edge surface", uowProvider)
|
||||
}
|
||||
return src.EdgeReader()
|
||||
}
|
||||
|
||||
// addDependencyEdgesProxied asserts edges through the DependencyEditor role.
|
||||
//
|
||||
// skipPerEdgeCycleCheck is a separate argument from the --no-cycle-check flag
|
||||
|
|
@ -358,8 +372,8 @@ func runDepListProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
|
|||
}
|
||||
|
||||
// The multi-id edge listing is a different question with a different
|
||||
// answer shape — raw edge records keyed by source, printed per source —
|
||||
// and no role describes it. It keeps its own unit of work.
|
||||
// answer shape — raw edge records keyed by source, printed per source,
|
||||
// with a per-anchor miss — and it is on the EdgeReader role.
|
||||
if len(args) > 1 && direction == "down" {
|
||||
return runDepListRecordsProxiedServer(ctx, args, typeFilter)
|
||||
}
|
||||
|
|
@ -432,49 +446,35 @@ func runDepListProxiedServer(cmd *cobra.Command, ctx context.Context, args []str
|
|||
}
|
||||
|
||||
// runDepListRecordsProxiedServer answers `bd dep list a b c` with raw edge
|
||||
// records grouped by source. It is off the Relations role deliberately: the
|
||||
// role answers with the ISSUES on the far end of an anchor's edges, and this
|
||||
// prints the edges themselves, per source, for several sources at once.
|
||||
// Routing it through the role would mean N anchor probes and a hydration of
|
||||
// every neighbor this output never shows.
|
||||
// records grouped by source, on the EdgeReader role. It is off the Relations
|
||||
// role deliberately: that one answers with the ISSUES on the far end of ONE
|
||||
// anchor's edges, and this prints the edges themselves, per source, for several
|
||||
// sources at once.
|
||||
//
|
||||
// THIS ROUTE NOW REPORTS GHOST ANCHORS. It used to hand the raw arguments to
|
||||
// the dependency use case, which keys its answer by source and simply has no
|
||||
// entry for an id that names nothing — so a typo printed "<id> has no
|
||||
// dependencies" and a script read a clean graph. The role probes each anchor,
|
||||
// so the same typo now prints the warning the direct route has always printed
|
||||
// for an argument it could not resolve.
|
||||
//
|
||||
// It still resolves NOTHING: an id is passed exactly as the caller spelled it,
|
||||
// because this route has never done partial-id resolution and the role's ids
|
||||
// are exact.
|
||||
func runDepListRecordsProxiedServer(ctx context.Context, args []string, typeFilter string) error {
|
||||
uw, err := proxiedOpenReadUOW(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer uw.Close(ctx)
|
||||
|
||||
depMap, err := uw.DependencyUseCase().GetIssueDependencyRecords(ctx, args)
|
||||
reader, err := proxiedEdgeReader()
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
if jsonOutput {
|
||||
allDeps := []*types.Dependency{}
|
||||
for _, id := range args {
|
||||
for _, dep := range depMap[id] {
|
||||
if typeFilter == "" || string(dep.Type) == typeFilter {
|
||||
allDeps = append(allDeps, dep)
|
||||
}
|
||||
}
|
||||
}
|
||||
return outputJSON(allDeps)
|
||||
request := issueops.EdgeReadRequest{IDs: args}
|
||||
if typeFilter != "" {
|
||||
request.Types = []types.DependencyType{types.DependencyType(typeFilter)}
|
||||
}
|
||||
for _, id := range args {
|
||||
deps := depMap[id]
|
||||
if len(deps) == 0 {
|
||||
fmt.Printf("\n%s has no dependencies\n", id)
|
||||
continue
|
||||
}
|
||||
fmt.Printf("\n%s %s depends on:\n\n", ui.RenderAccent("📋"), id)
|
||||
for _, dep := range deps {
|
||||
if typeFilter != "" && string(dep.Type) != typeFilter {
|
||||
continue
|
||||
}
|
||||
fmt.Printf(" %s via %s\n", dep.DependsOnID, dep.Type)
|
||||
}
|
||||
result, err := reader.ReadEdges(ctx, request)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
fmt.Println()
|
||||
return nil
|
||||
return printDepListEdges(result.Anchors)
|
||||
}
|
||||
|
||||
func runDepTreeProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
|
||||
|
|
|
|||
|
|
@ -189,8 +189,8 @@ func runServe() error {
|
|||
// THIS IS THE ENFORCEMENT POINT, and it is now the only one. It used to be
|
||||
// redundant: httpapi.Listen took a unit-of-work provider or nothing, so deleting
|
||||
// this gate would still have left an embedded-backed server unbuildable.
|
||||
// httpapi.Config now also accepts the two issue roles as a database source and
|
||||
// the embedded store publishes both accessors, so it is buildable — and nothing
|
||||
// httpapi.Config now also accepts the issue roles as a database source and the
|
||||
// embedded store publishes every one of those accessors, so it is buildable — and nothing
|
||||
// downstream will catch a bypass here, because internal/httpapi cannot see the
|
||||
// backend behind a role. That is also why runServe builds a provider and never
|
||||
// hands Listen roles, which TestServeBuildsOnlyAProviderBackedServer pins.
|
||||
|
|
|
|||
|
|
@ -208,8 +208,8 @@ func useStorageModeGlobals(t *testing.T) {
|
|||
// httpapi.Listen once took a unit-of-work provider or nothing, and there is no
|
||||
// provider for the embedded backend, so an embedded-backed server could not be
|
||||
// built even with serveModeGate deleted. httpapi.Config now also accepts the
|
||||
// two issue roles as a database source, and the embedded store publishes both
|
||||
// accessors — so the shortest edit from here to a server whose per-request
|
||||
// issue roles as a database source, and the embedded store publishes every one
|
||||
// of those accessors — so the shortest edit from here to a server whose per-request
|
||||
// atomicity claim is false is handing Listen the roles off the store the root
|
||||
// command already opened. internal/httpapi will not catch it: a role is an
|
||||
// interface, and nothing about one says which backend is behind it.
|
||||
|
|
@ -258,7 +258,7 @@ func TestServeBuildsOnlyAProviderBackedServer(t *testing.T) {
|
|||
continue
|
||||
}
|
||||
switch key.Name {
|
||||
case "Reader", "Claimer":
|
||||
case "Reader", "Claimer", "EdgeReader":
|
||||
t.Errorf("%s: bd serve sets httpapi.Config.%s. The roles source bypasses the unit-of-work "+
|
||||
"provider serveModeGate vouched for, and internal/httpapi cannot tell an embedded-backed "+
|
||||
"role from any other — read serveModeGate before changing this",
|
||||
|
|
|
|||
|
|
@ -70,6 +70,17 @@ Twelve steps. Steps 1-9 are the role; 10-12 are what makes it the ONLY way in.
|
|||
(`CanonicalCyclePaths`, `BuildCycles`), so they are pinned in milliseconds
|
||||
without a database and the conformance contract is left to assert what only a
|
||||
real backend can show.
|
||||
**Unless the role needs ONE TRANSACTION.** A body that must read twice and
|
||||
have both reads see one snapshot — an existence probe plus the read it
|
||||
qualifies, which is what `Relations` and `EdgeReader` both do — cannot live
|
||||
above `storage.DoltStorage`, because that interface publishes no way to scope
|
||||
two calls to a transaction. Those bodies are `Validate…`/`Execute…InTx`
|
||||
functions in `internal/storage/issueops` (`relations.go`, `edges.go`) and
|
||||
each store's accessor wraps them in its own `withReadTx`/`withConn`. dolt and
|
||||
embeddeddolt still share ONE body, which is what step 3 is for; only its
|
||||
address differs. There is no step-12 depguard entry to add for one of these
|
||||
— the shared function takes a transaction, so no front door can call it at
|
||||
all.
|
||||
|
||||
4. **The unit-of-work body and its source interface.**
|
||||
`internal/storage/uow/<role>.go`, declaring `type <Role>Source interface {
|
||||
|
|
|
|||
|
|
@ -81,7 +81,7 @@ type ContextResponse struct {
|
|||
// BeadsDir Absolute path of the served workspace's `.beads` directory. A host path, kept because it is the single-workspace server's only workspace-identity handshake; disclosing it to network peers is part of what an operator accepts when binding beyond loopback.
|
||||
BeadsDir string `json:"beads_dir"`
|
||||
|
||||
// Capabilities The operations this server actually implements, derived from its route table. v0's vocabulary is `ready.list`, `issues.list`, `issues.get`, `issues.claim`, `config.list`, `config.get`; it grows `issues.get`, `issues.claim`, `dependencies.cycles`; it grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation — never the version string.
|
||||
// Capabilities The operations this server actually implements, derived from its route table. v0's vocabulary is `ready.list`, `issues.list`, `issues.get`, `issues.claim`, `stats.get`, `config.list`, `config.get`, `dependencies.cycles`, `dependencies.list`; it grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation — never the version string.
|
||||
Capabilities []string `json:"capabilities"`
|
||||
|
||||
// Database Logical database name (not a host or a DSN).
|
||||
|
|
@ -124,6 +124,19 @@ type CyclesPage struct {
|
|||
// Dependency A dependency edge between two issues.
|
||||
type Dependency = types.Dependency
|
||||
|
||||
// DependencyEdges The stored edges of the named issues, plus the ids that named nothing. It is NOT a page: this operation has no limit and no cursor, because the number of issues asked about is what bounds it.
|
||||
type DependencyEdges struct {
|
||||
// Items Every matching edge, flattened across the named issues rather than keyed by source — the same flat array `bd dep list a b c --json` emits, so the two surfaces are one compatibility domain. Group by `issue_id` to recover the per-source view. Empty array (never null) when nothing matches.
|
||||
//
|
||||
// The order is by the named issues in the order the request named them, and within each issue by target id.
|
||||
Items []Dependency `json:"items"`
|
||||
|
||||
// Missing The requested `issue_id` values that name neither an issue nor a wisp, in the order they were named. Empty array (never null) when every named issue exists.
|
||||
//
|
||||
// An id here contributes no `items`, and the absence of an id here is NOT a claim that it has edges — an issue that exists and depends on nothing is in neither list.
|
||||
Missing []string `json:"missing"`
|
||||
}
|
||||
|
||||
// Health defines model for Health.
|
||||
type Health struct {
|
||||
Status HealthStatus `json:"status"`
|
||||
|
|
@ -265,6 +278,23 @@ type NotFound = Problem
|
|||
// Unavailable RFC 9457 problem detail. This is the only error shape on this surface. The core declares `type`; this server never emits it, so `about:blank` is implied throughout.
|
||||
type Unavailable = Problem
|
||||
|
||||
// ListDependenciesParams defines parameters for ListDependencies.
|
||||
type ListDependenciesParams struct {
|
||||
// IssueId The issues to read edges for. Repeat the parameter; at least one is required and at most 100 are accepted, and either bound is a 400 `invalid_argument` with `param: "issue_id"`, `reason: "invalid_value"`.
|
||||
//
|
||||
// Each value must be an EXACT canonical issue id: there is no fuzzy, prefix or substring resolution on this surface, for the reason `GET /v0/beads/issues/{id}` gives. A value that matches nothing is reported in `missing` rather than refused. An empty value is a 400.
|
||||
//
|
||||
// Repeats collapse: an id named twice is one entry in `missing` at most once, and its edges appear once.
|
||||
IssueId []string `form:"issue_id" json:"issue_id"`
|
||||
|
||||
// Type Edge types to include. Repeat the parameter. Empty means every type.
|
||||
//
|
||||
// The vocabulary is OPEN — a workspace configures its own edge types — so an unrecognized value is not an error here: it simply matches no edge. What IS refused, with a 400 `invalid_argument`, is a value no edge could ever carry: empty, or longer than the column.
|
||||
//
|
||||
// The filter narrows EDGES, never the named issues. An issue whose every edge the filter rejects is still not in `missing`.
|
||||
Type *[]string `form:"type,omitempty" json:"type,omitempty"`
|
||||
}
|
||||
|
||||
// ListIssuesParams defines parameters for ListIssues.
|
||||
type ListIssuesParams struct {
|
||||
// Status Status filter. Repeat the parameter, or pass a comma-separated list. Custom statuses configured for the workspace are honored.
|
||||
|
|
|
|||
|
|
@ -357,6 +357,9 @@ var (
|
|||
_ uow.IssueReaderSource = timedProvider{}
|
||||
_ uow.IssueClaimerSource = timedProvider{}
|
||||
_ uow.CycleDetectorSource = timedProvider{}
|
||||
_ uow.IssueReaderSource = timedProvider{}
|
||||
_ uow.IssueClaimerSource = timedProvider{}
|
||||
_ uow.EdgeReaderSource = timedProvider{}
|
||||
)
|
||||
|
||||
// IssueReader builds the reader OVER THIS WRAPPER rather than delegating to the
|
||||
|
|
@ -414,6 +417,14 @@ func (p timedProvider) CycleDetector() (issueops.CycleDetector, error) {
|
|||
return uow.NewCycleDetector(p)
|
||||
}
|
||||
|
||||
// EdgeReader builds the stored-edge reader OVER THIS WRAPPER, for the same
|
||||
// reason and with the same hazard as the two above: the role opens one unit of
|
||||
// work per call, and it must go through NewUOW below or the dependencies route
|
||||
// reports uow_ms=0.000.
|
||||
func (p timedProvider) EdgeReader() (issueops.EdgeReader, error) {
|
||||
return uow.NewEdgeReader(p)
|
||||
}
|
||||
|
||||
func (p timedProvider) NewUOW(ctx context.Context) (uow.UnitOfWork, error) {
|
||||
start := time.Now()
|
||||
uw, err := p.inner.NewUOW(ctx)
|
||||
|
|
|
|||
124
internal/httpapi/edges.go
Normal file
124
internal/httpapi/edges.go
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/steveyegge/beads/internal/httpapi/apigen"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// maxDependencyAnchors bounds how many issues one call may ask about.
|
||||
//
|
||||
// It is the operation's ONLY size bound and it is deliberately on the QUESTION
|
||||
// rather than on the answer. `bd dep list` takes no limit, so a `limit`
|
||||
// parameter here would make the two front doors answer differently by default;
|
||||
// a cap on the answer with no cursor behind it would truncate with no way to
|
||||
// fetch the rest. Bounding the anchors bounds the work without doing either,
|
||||
// and it is the same shape of bound the document states.
|
||||
const maxDependencyAnchors = 100
|
||||
|
||||
// handleListDependencies answers GET /v0/beads/dependencies.
|
||||
//
|
||||
// Everything below the wire is on issueops.EdgeReader: which plane each anchor
|
||||
// is probed on, whether an absent anchor is a miss or an error, the type
|
||||
// filter, the edge order, and the de-duplication of a repeated id. What stays
|
||||
// here is transport — decoding two repeatable parameters, the size bound, and
|
||||
// flattening the role's per-anchor answer onto the flat array `bd dep list
|
||||
// --json` emits.
|
||||
func (s *Server) handleListDependencies(w http.ResponseWriter, r *http.Request) {
|
||||
q := newQuery(r.URL.Query())
|
||||
|
||||
ids := q.list("issue_id")
|
||||
req := issueops.EdgeReadRequest{IDs: ids}
|
||||
for _, depType := range q.list("type") {
|
||||
req.Types = append(req.Types, types.DependencyType(depType))
|
||||
}
|
||||
|
||||
if !s.acceptQuery(w, r, q) {
|
||||
return
|
||||
}
|
||||
// Both bounds are checked here rather than left to the role: they are this
|
||||
// operation's own limits on one shared process, not statements about what a
|
||||
// stored-edge read means, and the role answers an empty request with an
|
||||
// empty result rather than a refusal.
|
||||
if len(ids) == 0 {
|
||||
requestInfo(r.Context()).refuse("issue_id")
|
||||
s.fail(w, r, InvalidArgument("issue_id", ReasonInvalidValue, "name at least one issue_id"))
|
||||
return
|
||||
}
|
||||
if len(ids) > maxDependencyAnchors {
|
||||
requestInfo(r.Context()).refuse("issue_id")
|
||||
s.fail(w, r, InvalidArgument("issue_id", ReasonInvalidValue,
|
||||
fmt.Sprintf("at most %d issue_id values per request, got %d", maxDependencyAnchors, len(ids))))
|
||||
return
|
||||
}
|
||||
|
||||
rd, err := s.edgeReader(r)
|
||||
if err != nil {
|
||||
s.failErr(w, r, err)
|
||||
return
|
||||
}
|
||||
result, err := rd.ReadEdges(r.Context(), req)
|
||||
if err != nil {
|
||||
s.failEdgeReadErr(w, r, err, ids)
|
||||
return
|
||||
}
|
||||
writeJSON(w, wireEdges(result))
|
||||
}
|
||||
|
||||
// failEdgeReadErr answers a failed stored-edge read. The role's two
|
||||
// request-validation refusals — an empty id, an unusable dependency type — are
|
||||
// the caller's own input and reach the client as the 400 they are; everything
|
||||
// else keeps going through the one mapping in problem.go.
|
||||
//
|
||||
// It classifies on the SENTINEL rather than on prose, unlike the read handlers'
|
||||
// invalidFilterParam: this role publishes issueops.ErrValidation for exactly
|
||||
// those two cases, so there is no message to match. Which of the two parameters
|
||||
// is named comes from the request the handler still holds — an empty entry can
|
||||
// only have come from `issue_id`, so anything else is `type`.
|
||||
func (s *Server) failEdgeReadErr(w http.ResponseWriter, r *http.Request, err error, ids []string) {
|
||||
if !errors.Is(err, issueops.ErrValidation) {
|
||||
s.failErr(w, r, err)
|
||||
return
|
||||
}
|
||||
param := "type"
|
||||
for _, id := range ids {
|
||||
if id == "" {
|
||||
param = "issue_id"
|
||||
break
|
||||
}
|
||||
}
|
||||
requestInfo(r.Context()).refuse(param)
|
||||
s.fail(w, r, InvalidArgument(param, ReasonInvalidValue, err.Error()))
|
||||
}
|
||||
|
||||
// wireEdges flattens the role's per-anchor answer onto the wire envelope.
|
||||
//
|
||||
// The element type is an ALIAS of types.Dependency — the same struct the CLI's
|
||||
// --json marshals — so this copies a header and shares everything under it.
|
||||
// There is no second wire struct here and there must never be one.
|
||||
//
|
||||
// Both members are non-nil so the body carries `[]` rather than `null`, which
|
||||
// the document states for each of them.
|
||||
func wireEdges(result issueops.EdgeReadResult) apigen.DependencyEdges {
|
||||
body := apigen.DependencyEdges{
|
||||
Items: []apigen.Dependency{},
|
||||
Missing: []string{},
|
||||
}
|
||||
for _, anchor := range result.Anchors {
|
||||
if anchor.Missing {
|
||||
body.Missing = append(body.Missing, anchor.ID)
|
||||
continue
|
||||
}
|
||||
for _, edge := range anchor.Edges {
|
||||
if edge == nil {
|
||||
continue
|
||||
}
|
||||
body.Items = append(body.Items, *edge)
|
||||
}
|
||||
}
|
||||
return body
|
||||
}
|
||||
174
internal/httpapi/edges_test.go
Normal file
174
internal/httpapi/edges_test.go
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// These cover the transport half of GET /v0/beads/dependencies: the two size
|
||||
// refusals this operation owns, how a role refusal is named on the wire, and
|
||||
// the two never-null members. Everything below the wire — which plane an anchor
|
||||
// is probed on, what Missing means, the edge order — is the role's, and is
|
||||
// pinned by backend/conformance/edge_reader_contract.go at all three backends.
|
||||
|
||||
func newEdgesServer(t *testing.T, edges *roleEdgeReader) *testServer {
|
||||
t.Helper()
|
||||
return newTestServer(t, rolesConfig(Config{EdgeReader: edges}))
|
||||
}
|
||||
|
||||
// TestDependenciesFlattenTheRoleAnswer pins the wire projection: the per-anchor
|
||||
// answer becomes ONE flat array of edges in anchor order, which is the shape
|
||||
// `bd dep list a b c --json` emits, plus the ghost anchors on their own member.
|
||||
func TestDependenciesFlattenTheRoleAnswer(t *testing.T) {
|
||||
edges := &roleEdgeReader{result: issueops.EdgeReadResult{Anchors: []issueops.AnchorEdges{
|
||||
{ID: "bd-1", Edges: []*types.Dependency{
|
||||
{IssueID: "bd-1", DependsOnID: "bd-2", Type: types.DepBlocks},
|
||||
{IssueID: "bd-1", DependsOnID: "external:ticket-9", Type: types.DepRelated},
|
||||
}},
|
||||
{ID: "bd-3", Missing: true},
|
||||
{ID: "bd-4", Edges: []*types.Dependency{
|
||||
{IssueID: "bd-4", DependsOnID: "bd-2", Type: types.DepBlocks},
|
||||
}},
|
||||
}}}
|
||||
ts := newEdgesServer(t, edges)
|
||||
|
||||
body := decodeBody(t, ts.get(t, "/v0/beads/dependencies?issue_id=bd-1&issue_id=bd-3&issue_id=bd-4"))
|
||||
items, _ := body["items"].([]any)
|
||||
if len(items) != 3 {
|
||||
t.Fatalf("items = %v, want the three edges the role returned", body["items"])
|
||||
}
|
||||
want := []string{"bd-2", "external:ticket-9", "bd-2"}
|
||||
for i, item := range items {
|
||||
edge, _ := item.(map[string]any)
|
||||
if edge["depends_on_id"] != want[i] {
|
||||
t.Errorf("items[%d].depends_on_id = %v, want %q (anchor order, then the role's edge order)", i, edge["depends_on_id"], want[i])
|
||||
}
|
||||
// The row's surrogate key is not selected by this read, so `omitempty`
|
||||
// keeps it off the wire entirely rather than shipping an empty string.
|
||||
if _, present := edge["id"]; present {
|
||||
t.Errorf("items[%d] carries an `id`; the source-keyed read does not select it", i)
|
||||
}
|
||||
}
|
||||
if missing, _ := body["missing"].([]any); len(missing) != 1 || missing[0] != "bd-3" {
|
||||
t.Errorf("missing = %v, want just the ghost anchor", body["missing"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestDependenciesNeverAnswerNull pins both members as empty arrays rather than
|
||||
// null, which the document states for each of them: a client that ranges over
|
||||
// the answer must not have to nil-check either one.
|
||||
func TestDependenciesNeverAnswerNull(t *testing.T) {
|
||||
edges := &roleEdgeReader{result: issueops.EdgeReadResult{Anchors: []issueops.AnchorEdges{
|
||||
{ID: "bd-1"},
|
||||
}}}
|
||||
ts := newEdgesServer(t, edges)
|
||||
|
||||
raw := readAll(t, ts.get(t, "/v0/beads/dependencies?issue_id=bd-1"))
|
||||
if strings.Contains(raw, "null") {
|
||||
t.Fatalf("body = %s, want empty arrays rather than null", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDependenciesBoundTheQuestion pins the two refusals this operation owns.
|
||||
// They are on the ANCHOR COUNT rather than on the answer because `bd dep list`
|
||||
// has no limit, so a `limit` here would make the two front doors default
|
||||
// differently; see maxDependencyAnchors.
|
||||
func TestDependenciesBoundTheQuestion(t *testing.T) {
|
||||
edges := &roleEdgeReader{}
|
||||
ts := newEdgesServer(t, edges)
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
query string
|
||||
}{
|
||||
{"no issue_id at all", "/v0/beads/dependencies"},
|
||||
{"an empty issue_id list", "/v0/beads/dependencies?type=blocks"},
|
||||
{"more anchors than the cap", "/v0/beads/dependencies?" + repeatedIssueIDs(maxDependencyAnchors+1)},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
resp := ts.get(t, tc.query)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
body := decodeBody(t, resp)
|
||||
if body["code"] != string(CodeInvalidArgument) || body["param"] != "issue_id" || body["reason"] != string(ReasonInvalidValue) {
|
||||
t.Errorf("problem = %v, want invalid_argument on issue_id with invalid_value", body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The cap is a bound, not a rejection of large requests: exactly the cap
|
||||
// is served.
|
||||
if resp := ts.get(t, "/v0/beads/dependencies?"+repeatedIssueIDs(maxDependencyAnchors)); resp.StatusCode != http.StatusOK {
|
||||
t.Errorf("status = %d for exactly %d anchors, want 200: %s", resp.StatusCode, maxDependencyAnchors, readAll(t, resp))
|
||||
}
|
||||
}
|
||||
|
||||
// TestDependenciesRefuseAnUnknownParameter keeps this operation under the
|
||||
// document's uniform rule: an unrecognized filter parameter WIDENS the result
|
||||
// set, so it is version skew and not something to ignore.
|
||||
func TestDependenciesRefuseAnUnknownParameter(t *testing.T) {
|
||||
ts := newEdgesServer(t, &roleEdgeReader{})
|
||||
|
||||
resp := ts.get(t, "/v0/beads/dependencies?issue_id=bd-1&direction=up")
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
body := decodeBody(t, resp)
|
||||
if body["param"] != "direction" || body["reason"] != string(ReasonUnknownParameter) {
|
||||
t.Errorf("problem = %v, want unknown_parameter on direction", body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestADependencyRoleRefusalIsTheDocumentedBadRequest pins the mapping from the
|
||||
// role's ErrValidation onto the two parameters that can cause it.
|
||||
//
|
||||
// The role owns both refusals — an empty id, an unusable dependency type — so
|
||||
// the handler cannot re-derive which one happened from the error; it names the
|
||||
// parameter from the request it still holds. An empty entry can only have come
|
||||
// from issue_id, so anything else is type.
|
||||
func TestADependencyRoleRefusalIsTheDocumentedBadRequest(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
query string
|
||||
param string
|
||||
}{
|
||||
{"an empty id", "/v0/beads/dependencies?issue_id=bd-1&issue_id=", "issue_id"},
|
||||
{"an unusable type", "/v0/beads/dependencies?issue_id=bd-1&type=", "type"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ts := newEdgesServer(t, &roleEdgeReader{
|
||||
err: fmt.Errorf("read edges: %w", issueops.ErrValidation),
|
||||
})
|
||||
resp := ts.get(t, tc.query)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
body := decodeBody(t, resp)
|
||||
if body["code"] != string(CodeInvalidArgument) || body["param"] != tc.param || body["reason"] != string(ReasonInvalidValue) {
|
||||
t.Errorf("problem = %v, want invalid_argument on %q with invalid_value", body, tc.param)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Anything that is NOT a validation refusal keeps going through the one
|
||||
// mapping in problem.go rather than becoming a wrong 400.
|
||||
ts := newEdgesServer(t, &roleEdgeReader{err: errors.New("backend is unreachable")})
|
||||
if resp := ts.get(t, "/v0/beads/dependencies?issue_id=bd-1"); resp.StatusCode != http.StatusInternalServerError {
|
||||
t.Errorf("status = %d for an opaque role failure, want 500: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
}
|
||||
|
||||
func repeatedIssueIDs(n int) string {
|
||||
parts := make([]string, 0, n)
|
||||
for i := 0; i < n; i++ {
|
||||
parts = append(parts, fmt.Sprintf("issue_id=bd-%d", i))
|
||||
}
|
||||
return strings.Join(parts, "&")
|
||||
}
|
||||
|
|
@ -153,6 +153,11 @@ const (
|
|||
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"
|
||||
)
|
||||
|
||||
// operationCodes is the per-operation problem vocabulary: exactly the codes
|
||||
|
|
@ -196,6 +201,10 @@ var operationCodes = map[string][]Code{
|
|||
// 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},
|
||||
OpClaimIssue: {
|
||||
CodeInvalidArgument, CodeNotFound, CodeAlreadyClaimed, CodeNotClaimable,
|
||||
CodeBusy, CodeDBUnavailable, CodeInternal,
|
||||
|
|
|
|||
|
|
@ -38,6 +38,11 @@ import (
|
|||
// Ready and List need nothing from it: both return a VALUE, and wireItems
|
||||
// already drops a nil element out of a page. Get is the whole reason the type
|
||||
// exists.
|
||||
//
|
||||
// issueops.EdgeReader has no wrapper here for the same reason Ready and List
|
||||
// need nothing: it answers with a value, and wireEdges drops a nil edge. A role
|
||||
// that hands back no pointer cannot be dereferenced into a panic, so a checked
|
||||
// wrapper over it would be a layer with nothing to check.
|
||||
type checkedReader struct{ inner issueops.Reader }
|
||||
|
||||
// Ready passes the request through unchanged.
|
||||
|
|
|
|||
|
|
@ -20,6 +20,8 @@ import (
|
|||
// These tests cover the OTHER database source: a backend whose facade is a
|
||||
// store rather than a unit-of-work provider, served by handing Listen the roles
|
||||
// directly.
|
||||
// store rather than a unit-of-work provider, served by handing Listen the issue
|
||||
// roles directly.
|
||||
//
|
||||
// The fakes below implement issueops.Reader, issueops.Claimer,
|
||||
// issueops.WorkspaceConfig and issueops.StatsReporter and NOTHING else —
|
||||
|
|
@ -27,6 +29,11 @@ import (
|
|||
// produce a unit of work is still servable" is the property this whole seam
|
||||
// exists for. If any of them ever grows a NewUOW method these tests stop
|
||||
// proving it.
|
||||
// The fakes below implement issueops.Reader, issueops.Claimer and
|
||||
// issueops.EdgeReader and NOTHING else — deliberately not
|
||||
// uow.UnitOfWorkProvider, because "a backend that cannot produce a unit of work
|
||||
// is still servable" is the property this whole seam exists for. If any of them
|
||||
// ever grows a NewUOW method these tests stop proving it.
|
||||
|
||||
type roleReader struct {
|
||||
page issueops.IssuePage
|
||||
|
|
@ -81,6 +88,30 @@ func (r *roleReader) getRequests() []issueops.GetRequest {
|
|||
return append([]issueops.GetRequest(nil), r.get...)
|
||||
}
|
||||
|
||||
type roleEdgeReader struct {
|
||||
result issueops.EdgeReadResult
|
||||
err error
|
||||
|
||||
mu sync.Mutex
|
||||
reads []issueops.EdgeReadRequest
|
||||
}
|
||||
|
||||
func (e *roleEdgeReader) ReadEdges(_ context.Context, req issueops.EdgeReadRequest) (issueops.EdgeReadResult, error) {
|
||||
e.mu.Lock()
|
||||
e.reads = append(e.reads, req)
|
||||
e.mu.Unlock()
|
||||
if e.err != nil {
|
||||
return issueops.EdgeReadResult{}, e.err
|
||||
}
|
||||
return e.result, nil
|
||||
}
|
||||
|
||||
func (e *roleEdgeReader) edgeRequests() []issueops.EdgeReadRequest {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
return append([]issueops.EdgeReadRequest(nil), e.reads...)
|
||||
}
|
||||
|
||||
type roleClaimer struct {
|
||||
result issueops.ClaimResult
|
||||
err error
|
||||
|
|
@ -211,6 +242,9 @@ func rolesConfig(cfg Config) Config {
|
|||
if cfg.CycleDetector == nil {
|
||||
cfg.CycleDetector = &roleCycleDetector{}
|
||||
}
|
||||
if cfg.EdgeReader == nil {
|
||||
cfg.EdgeReader = &roleEdgeReader{}
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
|
|
@ -261,6 +295,10 @@ func countedPage() []*types.IssueWithCounts {
|
|||
// HALF-SET set is the dangerous one: a Config carrying a reader and no claimer
|
||||
// would bind, answer every read, and fail the one issue write on this surface
|
||||
// with a nil dereference — at claim time, in a handler, on a live server.
|
||||
// PARTIALLY-SET role set is the dangerous one: a Config carrying a reader and
|
||||
// no claimer would bind, answer every read, and fail the one write on this
|
||||
// surface with a nil dereference — at claim time, in a handler, on a live
|
||||
// server. Each role an operation reaches has a row here for the same reason.
|
||||
func TestListenRequiresExactlyOneDatabaseSource(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
|
|
@ -311,6 +349,11 @@ func TestListenRequiresExactlyOneDatabaseSource(t *testing.T) {
|
|||
cfg: rolesConfigWithout(func(c *Config) { c.CycleDetector = nil }),
|
||||
wantErr: "no database source",
|
||||
},
|
||||
{
|
||||
name: "no edge reader",
|
||||
cfg: rolesConfigWithout(func(c *Config) { c.EdgeReader = nil }),
|
||||
wantErr: "no database source",
|
||||
},
|
||||
{
|
||||
name: "a cycle detector alone",
|
||||
cfg: Config{CycleDetector: &roleCycleDetector{}},
|
||||
|
|
@ -376,13 +419,9 @@ func TestConfiguredRolesServeTheSameReadyBytesAsAProvider(t *testing.T) {
|
|||
readIssues: &recordingIssues{items: items},
|
||||
readConfig: emptyConfig{},
|
||||
}})
|
||||
viaRoles := newTestServer(t, Config{
|
||||
Reader: &roleReader{page: issueops.IssuePage{Items: items}},
|
||||
Claimer: &roleClaimer{},
|
||||
Settings: &roleSettings{},
|
||||
Stats: &roleStats{},
|
||||
CycleDetector: &roleCycleDetector{},
|
||||
})
|
||||
viaRoles := newTestServer(t, rolesConfig(Config{
|
||||
Reader: &roleReader{page: issueops.IssuePage{Items: items}},
|
||||
}))
|
||||
|
||||
for _, path := range []string{"/v0/beads/ready", "/v0/beads/issues"} {
|
||||
fromProvider := viaProvider.get(t, path)
|
||||
|
|
@ -419,7 +458,13 @@ func TestConfiguredRolesAnswerEveryDatabaseRoute(t *testing.T) {
|
|||
}
|
||||
blocked := 2
|
||||
reporter := &roleStats{summary: types.Statistics{TotalIssues: 7, OpenIssues: 5, BlockedIssues: &blocked}}
|
||||
ts := newTestServer(t, rolesConfig(Config{Reader: reader, Claimer: claimer, Settings: settings, Stats: reporter}))
|
||||
edges := &roleEdgeReader{result: issueops.EdgeReadResult{Anchors: []issueops.AnchorEdges{
|
||||
{ID: "bd-1", Edges: []*types.Dependency{{IssueID: "bd-1", DependsOnID: "bd-2", Type: types.DepBlocks}}},
|
||||
{ID: "bd-9", Missing: true},
|
||||
}}}
|
||||
ts := newTestServer(t, rolesConfig(Config{
|
||||
Reader: reader, Claimer: claimer, Settings: settings, Stats: reporter, EdgeReader: edges,
|
||||
}))
|
||||
|
||||
t.Run("ready", func(t *testing.T) {
|
||||
resp := ts.get(t, "/v0/beads/ready?sort=oldest")
|
||||
|
|
@ -569,6 +614,34 @@ func TestConfiguredRolesAnswerEveryDatabaseRoute(t *testing.T) {
|
|||
t.Errorf("the workspace-wide method was called %d times, want the 1 from the subtest above: an assignee asks the other question", len(got))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("dependencies", func(t *testing.T) {
|
||||
resp := ts.get(t, "/v0/beads/dependencies?issue_id=bd-1&issue_id=bd-9&type=blocks")
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
body := decodeBody(t, resp)
|
||||
items, _ := body["items"].([]any)
|
||||
if len(items) != 1 {
|
||||
t.Fatalf("items = %v, want the one edge the role returned", body["items"])
|
||||
}
|
||||
if edge, _ := items[0].(map[string]any); edge["issue_id"] != "bd-1" || edge["depends_on_id"] != "bd-2" {
|
||||
t.Errorf("edge = %v, want the row the role returned", items[0])
|
||||
}
|
||||
// The ghost anchor is on `missing`, not a 404 and not an item.
|
||||
missing, _ := body["missing"].([]any)
|
||||
if len(missing) != 1 || missing[0] != "bd-9" {
|
||||
t.Errorf("missing = %v, want the one anchor the role reported absent", body["missing"])
|
||||
}
|
||||
// The role is handed the request the wire named, not a rewritten one.
|
||||
reqs := edges.edgeRequests()
|
||||
if len(reqs) != 1 || len(reqs[0].IDs) != 2 || reqs[0].IDs[0] != "bd-1" || reqs[0].IDs[1] != "bd-9" {
|
||||
t.Fatalf("edge requests = %+v, want one carrying both ids in order", reqs)
|
||||
}
|
||||
if len(reqs[0].Types) != 1 || reqs[0].Types[0] != types.DepBlocks {
|
||||
t.Errorf("edge request types = %v, want the one the wire named", reqs[0].Types)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestConfiguredRolesKeepTheDocumentedRefusals: the error vocabulary belongs to
|
||||
|
|
@ -583,6 +656,7 @@ func TestConfiguredRolesKeepTheDocumentedRefusals(t *testing.T) {
|
|||
Settings: &roleSettings{},
|
||||
Stats: &roleStats{},
|
||||
CycleDetector: &roleCycleDetector{},
|
||||
EdgeReader: &roleEdgeReader{},
|
||||
})
|
||||
resp := ts.get(t, "/v0/beads/issues/bd-404")
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
|
|
@ -603,6 +677,7 @@ func TestConfiguredRolesKeepTheDocumentedRefusals(t *testing.T) {
|
|||
Settings: &roleSettings{},
|
||||
Stats: &roleStats{},
|
||||
CycleDetector: &roleCycleDetector{},
|
||||
EdgeReader: &roleEdgeReader{},
|
||||
})
|
||||
resp := ts.get(t, "/v0/beads/issues?status=bogus")
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
|
|
@ -619,6 +694,7 @@ func TestConfiguredRolesKeepTheDocumentedRefusals(t *testing.T) {
|
|||
Reader: &roleReader{},
|
||||
Stats: &roleStats{},
|
||||
CycleDetector: &roleCycleDetector{},
|
||||
EdgeReader: &roleEdgeReader{},
|
||||
Claimer: &roleClaimer{err: &issueops.ClaimConflictError{
|
||||
IssueID: "bd-1",
|
||||
Assignee: "bob",
|
||||
|
|
@ -647,6 +723,7 @@ func TestConfiguredRolesKeepTheDocumentedRefusals(t *testing.T) {
|
|||
Settings: &roleSettings{},
|
||||
Stats: &roleStats{},
|
||||
CycleDetector: &roleCycleDetector{},
|
||||
EdgeReader: &roleEdgeReader{},
|
||||
})
|
||||
resp := ts.get(t, "/v0/beads/ready")
|
||||
if resp.StatusCode != http.StatusInternalServerError {
|
||||
|
|
@ -750,6 +827,7 @@ func TestARoleThatAnswersWithNothingIsNotDereferenced(t *testing.T) {
|
|||
Settings: &roleSettings{},
|
||||
Stats: &roleStats{},
|
||||
CycleDetector: &roleCycleDetector{},
|
||||
EdgeReader: &roleEdgeReader{},
|
||||
})
|
||||
|
||||
got := silent.get(t, "/v0/beads/issues/bd-1")
|
||||
|
|
@ -779,6 +857,7 @@ func TestARoleThatAnswersWithNothingIsNotDereferenced(t *testing.T) {
|
|||
Settings: &roleSettings{},
|
||||
Stats: &roleStats{},
|
||||
CycleDetector: &roleCycleDetector{},
|
||||
EdgeReader: &roleEdgeReader{},
|
||||
})
|
||||
|
||||
resp := ts.claim(t, claimPath, `{"actor":"alice"}`)
|
||||
|
|
@ -845,16 +924,11 @@ func TestListenRefusesARoleThatFiresTheWorkspaceHooks(t *testing.T) {
|
|||
}
|
||||
|
||||
listen := func(cl issueops.Claimer) (*Server, error) {
|
||||
return Listen(Config{
|
||||
Addr: "127.0.0.1:0",
|
||||
Stdout: io.Discard,
|
||||
Stderr: io.Discard,
|
||||
Reader: &roleReader{},
|
||||
Claimer: cl,
|
||||
Settings: &roleSettings{},
|
||||
Stats: &roleStats{},
|
||||
CycleDetector: &roleCycleDetector{},
|
||||
})
|
||||
cfg := rolesConfig(Config{Claimer: cl})
|
||||
cfg.Addr = "127.0.0.1:0"
|
||||
cfg.Stdout = io.Discard
|
||||
cfg.Stderr = io.Discard
|
||||
return Listen(cfg)
|
||||
}
|
||||
|
||||
if _, err := listen(fromTheStore); err == nil {
|
||||
|
|
|
|||
|
|
@ -127,6 +127,14 @@ var routeTable = []route{
|
|||
implemented: true,
|
||||
handler: (*Server).handleGetSetting,
|
||||
},
|
||||
{
|
||||
op: OpListDependencies,
|
||||
method: http.MethodGet,
|
||||
pattern: "/v0/beads/dependencies",
|
||||
capability: "dependencies.list",
|
||||
implemented: true,
|
||||
handler: (*Server).handleListDependencies,
|
||||
},
|
||||
{
|
||||
op: OpClaimIssue,
|
||||
method: http.MethodPost,
|
||||
|
|
|
|||
|
|
@ -123,8 +123,12 @@ type Config struct {
|
|||
// Reader, Claimer, Settings and Stats are the roles this server answers
|
||||
// from, for a backend whose facade is a STORE rather than a unit-of-work
|
||||
// provider. sourceRoles is the authoritative list.
|
||||
// Reader, Claimer and EdgeReader are the issue roles this server answers
|
||||
// from, for a backend whose facade is a STORE rather than a unit-of-work
|
||||
// provider.
|
||||
//
|
||||
// Set them together, and only when Provider is nil: they are the other
|
||||
// Set them all together, and only when Provider is nil: they are the other
|
||||
// complete database source, not an override of one. Listen refuses every
|
||||
// other combination, including a PARTIAL set — a reader without a claimer
|
||||
// would bind, answer every read, and fail the one write on this surface with
|
||||
|
|
@ -135,6 +139,11 @@ type Config struct {
|
|||
// another field here and another one this source must carry, because a
|
||||
// database source that answers some operations and faults on others is not
|
||||
// a source.
|
||||
// other combination, including a partially-set set — a server missing one
|
||||
// role would bind, answer every other route, and fail that one with a nil
|
||||
// dereference inside a handler on a live server. The set grows by one each
|
||||
// time an operation reaches a role this source does not yet carry, and it
|
||||
// grows in the same change as the operation for exactly that reason.
|
||||
//
|
||||
// A caller with a store takes them off the store's own accessors, and WHICH
|
||||
// store value it takes them off is the whole question. Every decorator a
|
||||
|
|
@ -154,6 +163,8 @@ type Config struct {
|
|||
// wc, err := src.WorkspaceConfig()
|
||||
// st, err := src.StatsReporter()
|
||||
// httpapi.Listen(httpapi.Config{Reader: rd, Claimer: cl, Settings: wc, Stats: st, ...})
|
||||
// ed, err := src.EdgeReader()
|
||||
// httpapi.Listen(httpapi.Config{Reader: rd, Claimer: cl, EdgeReader: ed, ...})
|
||||
//
|
||||
// Listen refuses a hook-firing role rather than trusting the paragraph
|
||||
// above — see checkDatabaseSource.
|
||||
|
|
@ -173,22 +184,18 @@ type Config struct {
|
|||
// (see Server.reader) — and a role reached this way opens none through this
|
||||
// server, so a rebuild would buy nothing.
|
||||
//
|
||||
// Settings and Stats join them for the same reason Claimer does, and the
|
||||
// "set them together" rule covers all of them: this surface publishes two
|
||||
// settings operations and a summary operation, so a Reader and a Claimer
|
||||
// without them would bind, answer every issue route, and fail those routes
|
||||
// with a nil dereference inside a handler.
|
||||
// Every one of these is required for the reason the half-set pair is
|
||||
// refused: a server that binds while unable to answer an operation its own
|
||||
// capability list advertises is the failure this check exists to prevent,
|
||||
// and a nil role would produce it on the first request to that route
|
||||
// instead of at startup. Take them all off the same store, beneath the hook
|
||||
// layer.
|
||||
// layer. sourceRoles is the authoritative list.
|
||||
Reader issueops.Reader
|
||||
Claimer issueops.Claimer
|
||||
Settings issueops.WorkspaceConfig
|
||||
Stats issueops.StatsReporter
|
||||
CycleDetector issueops.CycleDetector
|
||||
EdgeReader issueops.EdgeReader
|
||||
// Workspace is the startup snapshot GET /v0/beads/context answers from.
|
||||
// Only the allowlisted fields are ever serialized — see contextResponse,
|
||||
// which names the whole set and the reasons for the exclusions.
|
||||
|
|
@ -220,11 +227,16 @@ type Server struct {
|
|||
// exactly when provider is nil. They are what reader(), claimer() and
|
||||
// cycleDetector() hand back on the store-shaped source; the names differ
|
||||
// from those methods because a struct cannot carry both.
|
||||
// issueReader, issueClaimer and issueEdges are the configured roles, set
|
||||
// exactly when provider is nil. They are what reader(), claimer() and
|
||||
// edgeReader() hand back on the store-shaped source; the names differ from
|
||||
// those methods because a struct cannot carry both.
|
||||
issueReader issueops.Reader
|
||||
issueClaimer issueops.Claimer
|
||||
settings issueops.WorkspaceConfig
|
||||
issueStats issueops.StatsReporter
|
||||
issueCycles issueops.CycleDetector
|
||||
issueEdges issueops.EdgeReader
|
||||
|
||||
listener net.Listener
|
||||
http *http.Server
|
||||
|
|
@ -326,6 +338,7 @@ func Listen(cfg Config) (*Server, error) {
|
|||
settings: cfg.Settings,
|
||||
issueStats: cfg.Stats,
|
||||
issueCycles: cfg.CycleDetector,
|
||||
issueEdges: cfg.EdgeReader,
|
||||
|
||||
sem: make(chan struct{}, maxInflight),
|
||||
semTimeout: semAcquireTimeout,
|
||||
|
|
@ -387,6 +400,11 @@ func Listen(cfg Config) (*Server, error) {
|
|||
// live server. A missing settings or summary role is the same failure on a
|
||||
// different route, which is why the set is all-or-nothing rather than a
|
||||
// required pair plus optional extras.
|
||||
// provider, or the issue roles. A PARTIALLY-SET role set is refused with the
|
||||
// same message as none at all, because it is the same mistake and the failure
|
||||
// it would otherwise produce is the worst shape available — a config missing
|
||||
// one role binds, answers every other route, and fails that one with a nil
|
||||
// dereference in a handler on a live server.
|
||||
//
|
||||
// Both together is refused rather than resolved by precedence: a caller that
|
||||
// set both holds two different opinions about where this server reads from, and
|
||||
|
|
@ -413,12 +431,12 @@ func Listen(cfg Config) (*Server, error) {
|
|||
// as this check is concerned, exactly as it was when the check was a hand-
|
||||
// written boolean per role.
|
||||
func sourceRoles(cfg Config) []any {
|
||||
return []any{cfg.Reader, cfg.Claimer, cfg.Settings, cfg.Stats, cfg.CycleDetector}
|
||||
return []any{cfg.Reader, cfg.Claimer, cfg.Settings, cfg.Stats, cfg.CycleDetector, cfg.EdgeReader}
|
||||
}
|
||||
|
||||
// roleSourceNames spells sourceRoles for the refusal message, in the same
|
||||
// order, so a caller reading the error learns the whole set it must pass.
|
||||
const roleSourceNames = "Reader, Claimer, Settings, Stats and CycleDetector"
|
||||
const roleSourceNames = "Reader, Claimer, Settings, Stats, CycleDetector and EdgeReader"
|
||||
|
||||
func anyRoleSet(cfg Config) bool {
|
||||
return slices.ContainsFunc(sourceRoles(cfg), func(r any) bool { return r != nil })
|
||||
|
|
@ -621,6 +639,24 @@ func (s *Server) workspaceConfig(r *http.Request) (issueops.WorkspaceConfig, err
|
|||
return src.WorkspaceConfig()
|
||||
}
|
||||
|
||||
// edgeReader returns the guarded stored-edge surface for one request.
|
||||
//
|
||||
// It is the third of the same shape, for the same reasons: the configured role
|
||||
// on the roles source, and on the provider source one built per request so its
|
||||
// units of work are timed into THIS request's log line, held by INTERFACE so
|
||||
// uow.EdgeReaderSource is load-bearing rather than decorative.
|
||||
//
|
||||
// There is no checked wrapper here, and roles.go says why: this role answers
|
||||
// with a VALUE, so no handler dereferences a pointer it returned. checkedReader
|
||||
// exists for Get alone.
|
||||
func (s *Server) edgeReader(r *http.Request) (issueops.EdgeReader, error) {
|
||||
if s.provider == nil {
|
||||
return s.issueEdges, nil
|
||||
}
|
||||
var src uow.EdgeReaderSource = timedProvider{inner: s.provider, rec: requestInfo(r.Context())}
|
||||
return src.EdgeReader()
|
||||
}
|
||||
|
||||
// WithUOW runs fn inside one unit of work and guarantees the rollback.
|
||||
//
|
||||
// The close context is DETACHED on purpose. Close sends ROLLBACK on the pinned
|
||||
|
|
|
|||
|
|
@ -577,8 +577,8 @@ func TestCapabilitiesAdvertiseEveryImplementedOperation(t *testing.T) {
|
|||
got = append(got, c.(string))
|
||||
}
|
||||
want := []string{
|
||||
"config.get", "config.list", "dependencies.cycles", "issues.claim",
|
||||
"issues.get", "issues.list", "ready.list", "stats.get",
|
||||
"config.get", "config.list", "dependencies.cycles", "dependencies.list",
|
||||
"issues.claim", "issues.get", "issues.list", "ready.list", "stats.get",
|
||||
}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Errorf("capabilities = %v, want %v", got, want)
|
||||
|
|
|
|||
|
|
@ -956,6 +956,111 @@ paths:
|
|||
'503':
|
||||
$ref: '#/components/responses/Unavailable'
|
||||
|
||||
/v0/beads/dependencies:
|
||||
get:
|
||||
operationId: listDependencies
|
||||
summary: List the stored dependency edges of several issues
|
||||
description: >-
|
||||
The STORED EDGE ROWS whose source is each named issue — the answer
|
||||
`bd dep list a b c` gives, and the same `Dependency` elements that
|
||||
command's `--json` emits.
|
||||
|
||||
|
||||
THESE ARE ROWS, NOT NEIGHBOURS, and that is the difference from the
|
||||
`dependencies` member of `GET /v0/beads/issues/{id}`'s issue body. A
|
||||
dependency target may be an `external:` reference or an id belonging to
|
||||
another repository, and this database holds no issue for either; such
|
||||
an edge is returned here with its target spelled exactly as stored, and
|
||||
nothing is looked up on the far end. The `id` member of each element is
|
||||
absent: the read behind this operation does not select the row's
|
||||
surrogate key, so the `(issue_id, depends_on_id, type)` triple is what
|
||||
identifies an edge on this surface.
|
||||
|
||||
|
||||
THE DIRECTION IS OUTGOING ONLY — what each issue depends on. There is
|
||||
no direction parameter: the inbound bulk read is a different read
|
||||
against a different key with its own de-duplication rule across the two
|
||||
dependency tables, and adding it later is additive.
|
||||
|
||||
|
||||
A NAMED ISSUE THAT DOES NOT EXIST IS NOT A 404. It is listed in
|
||||
`missing`, and the edges of the issues that do exist are still
|
||||
returned: a batch that failed on one absent id would throw away the
|
||||
answers for the ids that were found. An issue that exists and depends
|
||||
on nothing is absent from `missing` and contributes no `items`, which
|
||||
is the distinction this operation exists to publish — an empty edge
|
||||
list is otherwise indistinguishable from a typo, and the empty list is
|
||||
the common case.
|
||||
|
||||
|
||||
THERE IS NO `limit` AND NO CURSOR. `bd dep list` has no limit either,
|
||||
so one here would make the two surfaces answer differently by default;
|
||||
instead the QUESTION is bounded — at most 100 `issue_id` values per
|
||||
call — which bounds the answer without truncating it. Each issue's
|
||||
edges are unbounded, exactly as the `dependencies` member of
|
||||
`GET /v0/beads/issues/{id}` already is.
|
||||
parameters:
|
||||
- name: issue_id
|
||||
in: query
|
||||
description: >-
|
||||
The issues to read edges for. Repeat the parameter; at least one is
|
||||
required and at most 100 are accepted, and either bound is a 400
|
||||
`invalid_argument` with `param: "issue_id"`, `reason:
|
||||
"invalid_value"`.
|
||||
|
||||
|
||||
Each value must be an EXACT canonical issue id: there is no fuzzy,
|
||||
prefix or substring resolution on this surface, for the reason
|
||||
`GET /v0/beads/issues/{id}` gives. A value that matches nothing is
|
||||
reported in `missing` rather than refused. An empty value is a 400.
|
||||
|
||||
|
||||
Repeats collapse: an id named twice is one entry in `missing` at
|
||||
most once, and its edges appear once.
|
||||
style: form
|
||||
explode: true
|
||||
required: true
|
||||
schema:
|
||||
type: array
|
||||
minItems: 1
|
||||
maxItems: 100
|
||||
items:
|
||||
type: string
|
||||
- name: type
|
||||
in: query
|
||||
description: >-
|
||||
Edge types to include. Repeat the parameter. Empty means every
|
||||
type.
|
||||
|
||||
|
||||
The vocabulary is OPEN — a workspace configures its own edge types
|
||||
— so an unrecognized value is not an error here: it simply matches
|
||||
no edge. What IS refused, with a 400 `invalid_argument`, is a value
|
||||
no edge could ever carry: empty, or longer than the column.
|
||||
|
||||
|
||||
The filter narrows EDGES, never the named issues. An issue whose
|
||||
every edge the filter rejects is still not in `missing`.
|
||||
style: form
|
||||
explode: true
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
responses:
|
||||
'200':
|
||||
description: The stored edges of the named issues.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/DependencyEdges'
|
||||
'400':
|
||||
$ref: '#/components/responses/InvalidArgument'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalError'
|
||||
'503':
|
||||
$ref: '#/components/responses/Unavailable'
|
||||
|
||||
components:
|
||||
|
||||
parameters:
|
||||
|
|
@ -1804,8 +1909,8 @@ components:
|
|||
description: >-
|
||||
The operations this server actually implements, derived from its
|
||||
route table. v0's vocabulary is `ready.list`, `issues.list`,
|
||||
`issues.get`, `issues.claim`, `config.list`, `config.get`; it grows
|
||||
`issues.get`, `issues.claim`, `dependencies.cycles`; it grows
|
||||
`issues.get`, `issues.claim`, `stats.get`, `config.list`,
|
||||
`config.get`, `dependencies.cycles`, `dependencies.list`; it grows
|
||||
additively, and an operation never appears here unless it is fully
|
||||
implemented. This is how a client checks for an operation — never
|
||||
the version string.
|
||||
|
|
@ -1958,6 +2063,41 @@ components:
|
|||
answer rather than echoed from the request: `skip_blocked` is a
|
||||
hint, and a backend with no cheaper path answers with the full
|
||||
numbers and this flag false.
|
||||
DependencyEdges:
|
||||
type: object
|
||||
description: >-
|
||||
The stored edges of the named issues, plus the ids that named nothing.
|
||||
It is NOT a page: this operation has no limit and no cursor, because
|
||||
the number of issues asked about is what bounds it.
|
||||
required: [items, missing]
|
||||
properties:
|
||||
items:
|
||||
type: array
|
||||
description: >-
|
||||
Every matching edge, flattened across the named issues rather than
|
||||
keyed by source — the same flat array `bd dep list a b c --json`
|
||||
emits, so the two surfaces are one compatibility domain. Group by
|
||||
`issue_id` to recover the per-source view. Empty array (never null)
|
||||
when nothing matches.
|
||||
|
||||
|
||||
The order is by the named issues in the order the request named
|
||||
them, and within each issue by target id.
|
||||
items:
|
||||
$ref: '#/components/schemas/Dependency'
|
||||
missing:
|
||||
type: array
|
||||
description: >-
|
||||
The requested `issue_id` values that name neither an issue nor a
|
||||
wisp, in the order they were named. Empty array (never null) when
|
||||
every named issue exists.
|
||||
|
||||
|
||||
An id here contributes no `items`, and the absence of an id here is
|
||||
NOT a claim that it has edges — an issue that exists and depends on
|
||||
nothing is in neither list.
|
||||
items:
|
||||
type: string
|
||||
|
||||
ClaimRequest:
|
||||
type: object
|
||||
|
|
|
|||
|
|
@ -667,6 +667,10 @@ func (s *configStore) StatsReporter() (issueops.StatsReporter, error) {
|
|||
func (s *configStore) CycleDetector() (issueops.CycleDetector, error) {
|
||||
return nil, &storage.ErrUnsupported{Op: "CycleDetector", Backend: "jira-config-stub"}
|
||||
}
|
||||
|
||||
func (s *configStore) EdgeReader() (issueops.EdgeReader, error) {
|
||||
return nil, &storage.ErrUnsupported{Op: "EdgeReader", Backend: "jira-config-stub"}
|
||||
}
|
||||
func (s *configStore) SetConfig(_ context.Context, _, _ string) error { return nil }
|
||||
func (s *configStore) SetLocalMetadata(_ context.Context, _, _ string) error { return nil }
|
||||
func (s *configStore) GetLocalMetadata(_ context.Context, _ string) (string, error) {
|
||||
|
|
|
|||
90
internal/storage/dolt/edge_reader_contract_test.go
Normal file
90
internal/storage/dolt/edge_reader_contract_test.go
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
package dolt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/backend/conformance"
|
||||
)
|
||||
|
||||
// TestEdgeReaderContract runs the EdgeReader contract against the
|
||||
// server-backed store.
|
||||
//
|
||||
// The cases are subtests of one parent so the whole role suite shares one store
|
||||
// and one copy-on-write branch: each Run namespaces its ids under the fixture
|
||||
// prefix and names the exact anchors it asks about, and WritesNothing takes a
|
||||
// before/after history delta, which is only meaningful while the subtests run
|
||||
// sequentially. setupTestStore already marks the PARENT parallel; no subtest
|
||||
// here calls t.Parallel.
|
||||
func TestEdgeReaderContract(t *testing.T) {
|
||||
fixture, ctx, cleanup := newDoltEdgeReaderFixture(t, "edg")
|
||||
defer cleanup()
|
||||
|
||||
t.Run("AnswersOnePerAnchorInRequestOrder", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderAnswersOnePerAnchorInRequestOrder(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ReportsAMissingAnchorRatherThanFailing", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderReportsAMissingAnchorRatherThanFailing(t, ctx, fixture)
|
||||
})
|
||||
t.Run("DistinguishesNoEdgesFromNoAnchor", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderDistinguishesNoEdgesFromNoAnchor(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ReturnsTargetsVerbatim", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderReturnsTargetsVerbatim(t, ctx, fixture)
|
||||
})
|
||||
t.Run("CollapsesRepeatedAnchors", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderCollapsesRepeatedAnchors(t, ctx, fixture)
|
||||
})
|
||||
t.Run("OrdersEdgesByTarget", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderOrdersEdgesByTarget(t, ctx, fixture)
|
||||
})
|
||||
t.Run("FiltersEdgesNotAnchors", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderFiltersEdgesNotAnchors(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ReadsBothPlanes", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderReadsBothPlanes(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ResolvesExactIDsOnly", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderResolvesExactIDsOnly(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AnswersAnEmptyRequest", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderAnswersAnEmptyRequest(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RefusesAnEmptyID", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderRefusesAnEmptyID(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RefusesAnUnusableType", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderRefusesAnUnusableType(t, ctx, fixture)
|
||||
})
|
||||
t.Run("LeavesTheRequestAlone", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderLeavesTheRequestAlone(t, ctx, fixture)
|
||||
})
|
||||
t.Run("WritesNothing", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderWritesNothing(t, ctx, fixture)
|
||||
})
|
||||
}
|
||||
|
||||
func newDoltEdgeReaderFixture(t *testing.T, prefix string) (conformance.EdgeReaderFixture, context.Context, func()) {
|
||||
t.Helper()
|
||||
store, storeCleanup := setupTestStore(t)
|
||||
ctx, cancel := testContext(t)
|
||||
reader, err := store.EdgeReader()
|
||||
if err != nil {
|
||||
cancel()
|
||||
storeCleanup()
|
||||
t.Fatalf("EdgeReader(): %v", err)
|
||||
}
|
||||
kit := newDoltRoleFixtureKit(store, prefix)
|
||||
fixture := conformance.EdgeReaderFixture{
|
||||
IssuePrefix: kit.IssuePrefix,
|
||||
EdgeReader: reader,
|
||||
CreateIssue: kit.CreateIssue,
|
||||
CreateWisp: kit.CreateWisp,
|
||||
AddDependency: kit.AddDependency,
|
||||
CountHistory: kit.CountHistory,
|
||||
}
|
||||
return fixture, ctx, func() {
|
||||
cancel()
|
||||
storeCleanup()
|
||||
}
|
||||
}
|
||||
53
internal/storage/dolt/edgereader.go
Normal file
53
internal/storage/dolt/edgereader.go
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
package dolt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
storageissueops "github.com/steveyegge/beads/internal/storage/issueops"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// EdgeReader returns the guarded stored-edge surface for this store.
|
||||
func (s *DoltStore) EdgeReader() (issueops.EdgeReader, error) {
|
||||
return newEdgeReader(s)
|
||||
}
|
||||
|
||||
// newEdgeReader returns guarded stored-edge reads backed by store.
|
||||
//
|
||||
// It is unexported, unlike NewIssueRelations beside it: a command holds the
|
||||
// storage.DoltStorage interface and reaches the role through the accessor
|
||||
// above, which is where each decorator adds its layer. There is no shared
|
||||
// constructor for the cmd-bd-role-constructors depguard rule to deny here
|
||||
// because the shared body is an InTx function — it needs a transaction this
|
||||
// store owns, so no front door can reach it at all.
|
||||
func newEdgeReader(store *DoltStore) (issueops.EdgeReader, error) {
|
||||
if store == nil {
|
||||
return nil, &storage.ErrUnsupported{Op: "newEdgeReader", Backend: "nil"}
|
||||
}
|
||||
return &edgeReader{store: store}, nil
|
||||
}
|
||||
|
||||
type edgeReader struct{ store *DoltStore }
|
||||
|
||||
var _ issueops.EdgeReader = (*edgeReader)(nil)
|
||||
|
||||
// ReadEdges runs the anchor probe and the edge read in ONE read transaction,
|
||||
// so an anchor cannot be reported missing by a probe that raced a create the
|
||||
// edge read then saw.
|
||||
func (r *edgeReader) ReadEdges(ctx context.Context, request issueops.EdgeReadRequest) (issueops.EdgeReadResult, error) {
|
||||
if err := storageissueops.ValidateEdgeReadRequest(request); err != nil {
|
||||
return issueops.EdgeReadResult{}, err
|
||||
}
|
||||
var result issueops.EdgeReadResult
|
||||
err := r.store.withReadTx(ctx, func(tx *sql.Tx) error {
|
||||
var err error
|
||||
result, err = storageissueops.ExecuteEdgeRead(ctx, tx, request)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return issueops.EdgeReadResult{}, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
86
internal/storage/embeddeddolt/edge_reader_contract_test.go
Normal file
86
internal/storage/embeddeddolt/edge_reader_contract_test.go
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
//go:build cgo
|
||||
|
||||
package embeddeddolt_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/backend/conformance"
|
||||
)
|
||||
|
||||
// TestEdgeReaderContract runs the EdgeReader contract against the embedded
|
||||
// store, which calls the SAME body the server-backed store does
|
||||
// (storage/issueops.ExecuteEdgeRead) and differs only in the engine underneath
|
||||
// and in how the read transaction is opened. That is what this wiring catches;
|
||||
// it is not an independent vote on the body.
|
||||
//
|
||||
// One environment for the whole suite: booting an embedded engine per case
|
||||
// would dominate the runtime, the ids are prefix-namespaced and every request
|
||||
// names its own anchors, and the history delta needs the subtests sequential
|
||||
// anyway.
|
||||
func TestEdgeReaderContract(t *testing.T) {
|
||||
skipUnlessEmbeddedDolt(t)
|
||||
te := newTestEnv(t, "edg")
|
||||
ctx := t.Context()
|
||||
fixture := newEmbeddedEdgeReaderFixture(t, te, "edg")
|
||||
|
||||
t.Run("AnswersOnePerAnchorInRequestOrder", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderAnswersOnePerAnchorInRequestOrder(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ReportsAMissingAnchorRatherThanFailing", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderReportsAMissingAnchorRatherThanFailing(t, ctx, fixture)
|
||||
})
|
||||
t.Run("DistinguishesNoEdgesFromNoAnchor", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderDistinguishesNoEdgesFromNoAnchor(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ReturnsTargetsVerbatim", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderReturnsTargetsVerbatim(t, ctx, fixture)
|
||||
})
|
||||
t.Run("CollapsesRepeatedAnchors", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderCollapsesRepeatedAnchors(t, ctx, fixture)
|
||||
})
|
||||
t.Run("OrdersEdgesByTarget", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderOrdersEdgesByTarget(t, ctx, fixture)
|
||||
})
|
||||
t.Run("FiltersEdgesNotAnchors", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderFiltersEdgesNotAnchors(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ReadsBothPlanes", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderReadsBothPlanes(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ResolvesExactIDsOnly", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderResolvesExactIDsOnly(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AnswersAnEmptyRequest", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderAnswersAnEmptyRequest(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RefusesAnEmptyID", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderRefusesAnEmptyID(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RefusesAnUnusableType", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderRefusesAnUnusableType(t, ctx, fixture)
|
||||
})
|
||||
t.Run("LeavesTheRequestAlone", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderLeavesTheRequestAlone(t, ctx, fixture)
|
||||
})
|
||||
t.Run("WritesNothing", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderWritesNothing(t, ctx, fixture)
|
||||
})
|
||||
}
|
||||
|
||||
func newEmbeddedEdgeReaderFixture(t *testing.T, te *testEnv, prefix string) conformance.EdgeReaderFixture {
|
||||
t.Helper()
|
||||
reader, err := te.store.EdgeReader()
|
||||
if err != nil {
|
||||
t.Fatalf("EdgeReader(): %v", err)
|
||||
}
|
||||
kit := newEmbeddedRoleFixtureKit(te, prefix)
|
||||
return conformance.EdgeReaderFixture{
|
||||
IssuePrefix: kit.IssuePrefix,
|
||||
EdgeReader: reader,
|
||||
CreateIssue: kit.CreateIssue,
|
||||
CreateWisp: kit.CreateWisp,
|
||||
AddDependency: kit.AddDependency,
|
||||
CountHistory: kit.CountHistory,
|
||||
}
|
||||
}
|
||||
50
internal/storage/embeddeddolt/edgereader.go
Normal file
50
internal/storage/embeddeddolt/edgereader.go
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
//go:build cgo
|
||||
|
||||
package embeddeddolt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
storageissueops "github.com/steveyegge/beads/internal/storage/issueops"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// EdgeReader returns the guarded stored-edge surface for this store.
|
||||
func (s *EmbeddedDoltStore) EdgeReader() (issueops.EdgeReader, error) {
|
||||
return newEdgeReader(s)
|
||||
}
|
||||
|
||||
// newEdgeReader returns guarded stored-edge reads backed by store. It is
|
||||
// unexported for the reason the server-backed sibling gives: the accessor above
|
||||
// is the door, because that is where each decorator adds its layer.
|
||||
func newEdgeReader(store *EmbeddedDoltStore) (issueops.EdgeReader, error) {
|
||||
if store == nil {
|
||||
return nil, &storage.ErrUnsupported{Op: "newEdgeReader", Backend: "nil"}
|
||||
}
|
||||
return &edgeReader{store: store}, nil
|
||||
}
|
||||
|
||||
type edgeReader struct{ store *EmbeddedDoltStore }
|
||||
|
||||
var _ issueops.EdgeReader = (*edgeReader)(nil)
|
||||
|
||||
// ReadEdges runs the anchor probe and the edge read on ONE connection, so an
|
||||
// anchor cannot be reported missing by a probe that raced a create the edge
|
||||
// read then saw.
|
||||
func (r *edgeReader) ReadEdges(ctx context.Context, request issueops.EdgeReadRequest) (issueops.EdgeReadResult, error) {
|
||||
if err := storageissueops.ValidateEdgeReadRequest(request); err != nil {
|
||||
return issueops.EdgeReadResult{}, err
|
||||
}
|
||||
var result issueops.EdgeReadResult
|
||||
err := r.store.withConn(ctx, false, func(tx *sql.Tx) error {
|
||||
var err error
|
||||
result, err = storageissueops.ExecuteEdgeRead(ctx, tx, request)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return issueops.EdgeReadResult{}, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
17
internal/storage/hook_edgereader.go
Normal file
17
internal/storage/hook_edgereader.go
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
package storage
|
||||
|
||||
import (
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// EdgeReader returns the inner store's stored-edge surface.
|
||||
//
|
||||
// It recurses, like every other accessor on this decorator, rather than being
|
||||
// absent: the accessor set is uniform across the chain, so a caller never has
|
||||
// to know which decorators a store is wearing. What it does NOT do is wrap the
|
||||
// result — reading edges fires no completion hooks, because nothing completed.
|
||||
// That is the same statement hook_issue_reader.go, hook_relations.go and
|
||||
// hook_counter.go make.
|
||||
func (h *HookFiringStore) EdgeReader() (issueops.EdgeReader, error) {
|
||||
return h.inner.EdgeReader()
|
||||
}
|
||||
184
internal/storage/issueops/edges.go
Normal file
184
internal/storage/issueops/edges.go
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
package issueops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// ValidateEdgeReadRequest applies the request rules every EdgeReader
|
||||
// implementation shares.
|
||||
//
|
||||
// There are only two, and both are about telling a caller's mistake from a
|
||||
// legitimately empty answer. An empty ID entry names nothing, so it is refused
|
||||
// rather than reported as a missing anchor with no name; an unusable dependency
|
||||
// type is refused rather than becoming a filter that silently matches nothing.
|
||||
// An empty ID SLICE is neither: it asks about no anchors and gets none back.
|
||||
func ValidateEdgeReadRequest(request publicops.EdgeReadRequest) error {
|
||||
for i, id := range request.IDs {
|
||||
if id == "" {
|
||||
return fmt.Errorf("%w: read edges id %d is empty", storage.ErrValidation, i)
|
||||
}
|
||||
}
|
||||
for i, depType := range request.Types {
|
||||
if !depType.IsValid() {
|
||||
return fmt.Errorf("%w: read edges type %d is not a usable dependency type (non-empty, max %d chars)",
|
||||
storage.ErrValidation, i, types.MaxDependencyTypeLen)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// EdgeReadAnchors is the de-duplicated anchor list a read runs against: the
|
||||
// request's ids with repeats collapsed onto their first mention.
|
||||
//
|
||||
// It is a shared function rather than a loop in each implementation because the
|
||||
// de-duplication decides the SHAPE of the answer — one entry per distinct id,
|
||||
// in first-mention order — and an implementation that skipped it would return a
|
||||
// different number of anchors than its sibling for the same request.
|
||||
func EdgeReadAnchors(ids []string) []string {
|
||||
seen := make(map[string]struct{}, len(ids))
|
||||
out := make([]string, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if _, dup := seen[id]; dup {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
out = append(out, id)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// FinishEdgeRead assembles the per-anchor answer from the two things every
|
||||
// implementation reads: which anchors exist, and the edges keyed by source.
|
||||
//
|
||||
// It is one function rather than two copies for the reason FinishRelatedPage
|
||||
// is: the type filter, the pinned order and the empty-versus-absent
|
||||
// distinction are the whole observable contract of this role, and an
|
||||
// implementation that applied them for itself is one the two will eventually
|
||||
// disagree about.
|
||||
//
|
||||
// THE ORDER is ascending by target id, with the edge type breaking a tie. The
|
||||
// row's own surrogate key is deliberately not a third term — the source-keyed
|
||||
// read does not select it, so it is empty on every row here and sorting by it
|
||||
// would be sorting by nothing.
|
||||
func FinishEdgeRead(anchors []string, present map[string]struct{}, edges map[string][]*types.Dependency, depTypes []types.DependencyType) publicops.EdgeReadResult {
|
||||
allowed := make(map[types.DependencyType]struct{}, len(depTypes))
|
||||
for _, depType := range depTypes {
|
||||
allowed[depType] = struct{}{}
|
||||
}
|
||||
|
||||
out := publicops.EdgeReadResult{Anchors: make([]publicops.AnchorEdges, 0, len(anchors))}
|
||||
for _, id := range anchors {
|
||||
_, exists := present[id]
|
||||
entry := publicops.AnchorEdges{ID: id, Missing: !exists, Edges: []*types.Dependency{}}
|
||||
// A missing anchor carries no edges even if rows are keyed to it: a
|
||||
// dependency row whose source has been deleted is orphaned data, and
|
||||
// reporting it under an anchor this call just said does not exist would
|
||||
// contradict the flag beside it.
|
||||
if exists {
|
||||
for _, edge := range edges[id] {
|
||||
if edge == nil {
|
||||
continue
|
||||
}
|
||||
if len(allowed) > 0 {
|
||||
if _, ok := allowed[edge.Type]; !ok {
|
||||
continue
|
||||
}
|
||||
}
|
||||
entry.Edges = append(entry.Edges, edge)
|
||||
}
|
||||
sort.SliceStable(entry.Edges, func(i, j int) bool {
|
||||
if entry.Edges[i].DependsOnID != entry.Edges[j].DependsOnID {
|
||||
return entry.Edges[i].DependsOnID < entry.Edges[j].DependsOnID
|
||||
}
|
||||
return entry.Edges[i].Type < entry.Edges[j].Type
|
||||
})
|
||||
}
|
||||
out.Anchors = append(out.Anchors, entry)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ExecuteEdgeRead returns each anchor's stored outgoing edges in tx. It is the
|
||||
// store-backed body behind the EdgeReader accessor; the unit-of-work provider
|
||||
// has its own, which reaches the same two reads through its use cases.
|
||||
//
|
||||
// The existence probe and the edge read share ONE transaction, which is what
|
||||
// lets AnchorEdges.Missing mean what it says: a probe in its own transaction
|
||||
// could report an anchor missing and then a second transaction could return
|
||||
// that anchor's edges, and the answer would contradict itself in a single
|
||||
// response body.
|
||||
func ExecuteEdgeRead(ctx context.Context, tx DBTX, request publicops.EdgeReadRequest) (publicops.EdgeReadResult, error) {
|
||||
anchors := EdgeReadAnchors(request.IDs)
|
||||
if len(anchors) == 0 {
|
||||
return publicops.EdgeReadResult{Anchors: []publicops.AnchorEdges{}}, nil
|
||||
}
|
||||
present, err := PresentIssueOrWispIDsInTx(ctx, tx, anchors)
|
||||
if err != nil {
|
||||
return publicops.EdgeReadResult{}, err
|
||||
}
|
||||
edges, err := GetDependencyRecordsForIssuesInTx(ctx, tx, anchors)
|
||||
if err != nil {
|
||||
return publicops.EdgeReadResult{}, err
|
||||
}
|
||||
return FinishEdgeRead(anchors, present, edges, request.Types), nil
|
||||
}
|
||||
|
||||
// PresentIssueOrWispIDsInTx reports which of ids exist, on either plane. It is
|
||||
// the batched form of RequireIssueOrWispInTx, and it answers with a set rather
|
||||
// than an error for the same reason the role reports Missing per anchor: a
|
||||
// batch that failed on the first absent id would throw away the answers for the
|
||||
// ids that were found.
|
||||
//
|
||||
// A missing wisps table is "no wisps", exactly as the single-id probe treats
|
||||
// it: older schemas predate that plane and an anchor there is simply not one.
|
||||
//
|
||||
//nolint:gosec // G201: table is one of two hardcoded literals; only ? placeholders in the IN clause.
|
||||
func PresentIssueOrWispIDsInTx(ctx context.Context, tx DBTX, ids []string) (map[string]struct{}, error) {
|
||||
present := make(map[string]struct{}, len(ids))
|
||||
if len(ids) == 0 {
|
||||
return present, nil
|
||||
}
|
||||
for _, table := range []string{"issues", "wisps"} {
|
||||
for start := 0; start < len(ids); start += queryBatchSize {
|
||||
end := start + queryBatchSize
|
||||
if end > len(ids) {
|
||||
end = len(ids)
|
||||
}
|
||||
batch := ids[start:end]
|
||||
placeholders := make([]string, len(batch))
|
||||
args := make([]any, len(batch))
|
||||
for i, id := range batch {
|
||||
placeholders[i] = "?"
|
||||
args[i] = id
|
||||
}
|
||||
rows, err := tx.QueryContext(ctx, fmt.Sprintf(
|
||||
"SELECT id FROM %s WHERE id IN (%s)", table, strings.Join(placeholders, ",")), args...)
|
||||
if err != nil {
|
||||
if isTableNotExistError(err) {
|
||||
break
|
||||
}
|
||||
return nil, fmt.Errorf("check issue existence in %s: %w", table, err)
|
||||
}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if scanErr := rows.Scan(&id); scanErr != nil {
|
||||
_ = rows.Close()
|
||||
return nil, fmt.Errorf("check issue existence in %s: scan: %w", table, scanErr)
|
||||
}
|
||||
present[id] = struct{}{}
|
||||
}
|
||||
_ = rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("check issue existence in %s: rows: %w", table, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return present, nil
|
||||
}
|
||||
|
|
@ -19,6 +19,7 @@ var roleAccessorNames = []string{
|
|||
"IssueLifecycle",
|
||||
"IssueReader",
|
||||
"IssueRelations",
|
||||
"EdgeReader",
|
||||
"Counter",
|
||||
"WorkspaceConfig",
|
||||
"StatsReporter",
|
||||
|
|
@ -72,6 +73,7 @@ type roleAccessorStore struct {
|
|||
lifecycle issueops.Lifecycle
|
||||
reader issueops.Reader
|
||||
relations issueops.Relations
|
||||
edges issueops.EdgeReader
|
||||
counter issueops.Counter
|
||||
settings issueops.WorkspaceConfig
|
||||
stats issueops.StatsReporter
|
||||
|
|
@ -89,6 +91,7 @@ func newRoleAccessorStore() *roleAccessorStore {
|
|||
lifecycle: sentinel,
|
||||
reader: sentinel,
|
||||
relations: sentinel,
|
||||
edges: sentinel,
|
||||
counter: sentinel,
|
||||
settings: sentinel,
|
||||
stats: sentinel,
|
||||
|
|
@ -114,7 +117,8 @@ func (s *roleAccessorStore) StatsReporter() (issueops.StatsReporter, error) {
|
|||
func (s *roleAccessorStore) CycleDetector() (issueops.CycleDetector, error) {
|
||||
return s.cycles, s.err
|
||||
}
|
||||
func (s *roleAccessorStore) Commenter() (issueops.Commenter, error) { return s.commenter, s.err }
|
||||
func (s *roleAccessorStore) EdgeReader() (issueops.EdgeReader, error) { return s.edges, s.err }
|
||||
func (s *roleAccessorStore) Commenter() (issueops.Commenter, error) { return s.commenter, s.err }
|
||||
func (s *roleAccessorStore) ReadyClaimer() (issueops.ReadyClaimer, error) {
|
||||
return s.claimer, s.err
|
||||
}
|
||||
|
|
@ -151,6 +155,9 @@ func (*roleAccessorSentinel) Get(context.Context, issueops.GetRequest) (*issueop
|
|||
func (*roleAccessorSentinel) Related(context.Context, issueops.RelatedRequest) ([]*issueops.RelatedIssue, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (*roleAccessorSentinel) ReadEdges(context.Context, issueops.EdgeReadRequest) (issueops.EdgeReadResult, error) {
|
||||
return issueops.EdgeReadResult{}, nil
|
||||
}
|
||||
func (*roleAccessorSentinel) Count(context.Context, issueops.CountRequest) (issueops.CountResult, error) {
|
||||
return issueops.CountResult{}, nil
|
||||
}
|
||||
|
|
@ -216,6 +223,12 @@ func (*roleAccessorSentinel) RemoveDependency(context.Context, issueops.RemoveDe
|
|||
// (hook_issue_reader.go, hook_relations.go, hook_counter.go,
|
||||
// hook_cycle_detector.go); this test pins that as a decision rather than
|
||||
// leaving it indistinguishable from the regression above.
|
||||
// The four read roles are asserted the OTHER way round on purpose. Reads fire
|
||||
// no completion hooks, so IssueReader, IssueRelations, EdgeReader and Counter
|
||||
// deliberately return the inner surface unwrapped (hook_issue_reader.go,
|
||||
// hook_relations.go, hook_edgereader.go, hook_counter.go); this test pins that
|
||||
// as a decision rather than leaving it indistinguishable from the regression
|
||||
// above.
|
||||
func TestHookFiringStoreWrapsTheWriteRolesAndPassesTheReadsThrough(t *testing.T) {
|
||||
inner := newRoleAccessorStore()
|
||||
store := NewHookFiringStore(inner, nil)
|
||||
|
|
@ -233,6 +246,7 @@ func TestHookFiringStoreWrapsTheWriteRolesAndPassesTheReadsThrough(t *testing.T)
|
|||
{"DependencyEditor", func() (any, error) { return store.DependencyEditor() }, inner.editor, true},
|
||||
{"IssueReader", func() (any, error) { return store.IssueReader() }, inner.reader, false},
|
||||
{"IssueRelations", func() (any, error) { return store.IssueRelations() }, inner.relations, false},
|
||||
{"EdgeReader", func() (any, error) { return store.EdgeReader() }, inner.edges, false},
|
||||
{"Counter", func() (any, error) { return store.Counter() }, inner.counter, false},
|
||||
{"WorkspaceConfig", func() (any, error) { return store.WorkspaceConfig() }, inner.settings, false},
|
||||
{"StatsReporter", func() (any, error) { return store.StatsReporter() }, inner.stats, false},
|
||||
|
|
@ -274,6 +288,7 @@ func TestHookFiringStoreRoleAccessorsPropagateInnerErrors(t *testing.T) {
|
|||
{"DependencyEditor", func() (any, error) { return store.DependencyEditor() }},
|
||||
{"IssueReader", func() (any, error) { return store.IssueReader() }},
|
||||
{"IssueRelations", func() (any, error) { return store.IssueRelations() }},
|
||||
{"EdgeReader", func() (any, error) { return store.EdgeReader() }},
|
||||
{"Counter", func() (any, error) { return store.Counter() }},
|
||||
{"WorkspaceConfig", func() (any, error) { return store.WorkspaceConfig() }},
|
||||
{"StatsReporter", func() (any, error) { return store.StatsReporter() }},
|
||||
|
|
|
|||
|
|
@ -185,6 +185,13 @@ type Storage interface {
|
|||
// anchor's neighbors. Reads fire no hooks, so the hook decorator's answer is
|
||||
// its inner store's unchanged, as it is for IssueReader.
|
||||
CycleDetector() (issueops.CycleDetector, error)
|
||||
// EdgeReader returns the guarded stored-edge surface for this store: raw
|
||||
// dependency rows for many anchors at once, keyed by source, with a
|
||||
// per-anchor miss. Its own role rather than a second IssueRelations method
|
||||
// because that one is single-anchor, answers with hydrated issues, and
|
||||
// refuses a missing anchor outright. Reads fire no hooks, as for
|
||||
// IssueReader.
|
||||
EdgeReader() (issueops.EdgeReader, error)
|
||||
|
||||
// Issue CRUD
|
||||
CreateIssue(ctx context.Context, issue *types.Issue, actor string) error
|
||||
|
|
|
|||
93
internal/storage/uow/edge_reader_contract_test.go
Normal file
93
internal/storage/uow/edge_reader_contract_test.go
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
package uow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/backend/conformance"
|
||||
)
|
||||
|
||||
// TestEdgeReaderContract runs the EdgeReader contract against the unit-of-work
|
||||
// provider — the one EdgeReader implementation that does not call
|
||||
// storage/issueops.ExecuteEdgeRead, so this is the wiring where a genuine body
|
||||
// divergence shows up. It probes anchor existence through two batched use-case
|
||||
// reads, one per plane, where the two store backends run one batched EXISTS
|
||||
// over both tables; that makes this the SECOND of two votes rather than the
|
||||
// third.
|
||||
//
|
||||
// One provider for the whole suite (each newUOWRoleFixtureProvider boots a real
|
||||
// Dolt sql-server) and NO t.Parallel: this backend has no per-test
|
||||
// copy-on-write branch, so dolt_log and the issues table are database-global
|
||||
// and a parallel subtest would corrupt another subtest's history delta.
|
||||
func TestEdgeReaderContract(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
fixture := newUOWEdgeReaderFixture(t, ctx, "edg")
|
||||
|
||||
t.Run("AnswersOnePerAnchorInRequestOrder", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderAnswersOnePerAnchorInRequestOrder(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ReportsAMissingAnchorRatherThanFailing", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderReportsAMissingAnchorRatherThanFailing(t, ctx, fixture)
|
||||
})
|
||||
t.Run("DistinguishesNoEdgesFromNoAnchor", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderDistinguishesNoEdgesFromNoAnchor(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ReturnsTargetsVerbatim", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderReturnsTargetsVerbatim(t, ctx, fixture)
|
||||
})
|
||||
t.Run("CollapsesRepeatedAnchors", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderCollapsesRepeatedAnchors(t, ctx, fixture)
|
||||
})
|
||||
t.Run("OrdersEdgesByTarget", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderOrdersEdgesByTarget(t, ctx, fixture)
|
||||
})
|
||||
t.Run("FiltersEdgesNotAnchors", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderFiltersEdgesNotAnchors(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ReadsBothPlanes", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderReadsBothPlanes(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ResolvesExactIDsOnly", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderResolvesExactIDsOnly(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AnswersAnEmptyRequest", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderAnswersAnEmptyRequest(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RefusesAnEmptyID", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderRefusesAnEmptyID(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RefusesAnUnusableType", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderRefusesAnUnusableType(t, ctx, fixture)
|
||||
})
|
||||
t.Run("LeavesTheRequestAlone", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderLeavesTheRequestAlone(t, ctx, fixture)
|
||||
})
|
||||
t.Run("WritesNothing", func(t *testing.T) {
|
||||
conformance.RunEdgeReaderWritesNothing(t, ctx, fixture)
|
||||
})
|
||||
}
|
||||
|
||||
func newUOWEdgeReaderFixture(t *testing.T, ctx context.Context, prefix string) conformance.EdgeReaderFixture {
|
||||
t.Helper()
|
||||
provider := newUOWRoleFixtureProvider(t, ctx, prefix)
|
||||
// Through the capability accessor, not NewEdgeReader: a provider that
|
||||
// stopped offering the role is the regression, and a constructor call would
|
||||
// hide it.
|
||||
source, ok := provider.(EdgeReaderSource)
|
||||
if !ok {
|
||||
t.Fatalf("provider %T does not offer the EdgeReader accessor", provider)
|
||||
}
|
||||
reader, err := source.EdgeReader()
|
||||
if err != nil {
|
||||
t.Fatalf("EdgeReader(): %v", err)
|
||||
}
|
||||
kit := newUOWRoleFixtureKit(provider, prefix)
|
||||
return conformance.EdgeReaderFixture{
|
||||
IssuePrefix: kit.IssuePrefix,
|
||||
EdgeReader: reader,
|
||||
CreateIssue: kit.CreateIssue,
|
||||
CreateWisp: kit.CreateWisp,
|
||||
AddDependency: kit.AddDependency,
|
||||
CountHistory: kit.CountHistory,
|
||||
}
|
||||
}
|
||||
84
internal/storage/uow/edgereader.go
Normal file
84
internal/storage/uow/edgereader.go
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
package uow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
storageissueops "github.com/steveyegge/beads/internal/storage/issueops"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// EdgeReaderSource is the capability accessor a unit-of-work provider offers
|
||||
// for the stored-edge role, the sibling of RelationsSource and CounterSource.
|
||||
type EdgeReaderSource interface {
|
||||
EdgeReader() (publicops.EdgeReader, error)
|
||||
}
|
||||
|
||||
// edgeReader answers stored-edge reads through a unit of work.
|
||||
type edgeReader struct {
|
||||
provider UnitOfWorkProvider
|
||||
}
|
||||
|
||||
// EdgeReader returns the guarded stored-edge surface for this provider.
|
||||
func (p *doltSQLProvider) EdgeReader() (publicops.EdgeReader, error) {
|
||||
return NewEdgeReader(p)
|
||||
}
|
||||
|
||||
// NewEdgeReader constructs public stored-edge reads backed by provider.
|
||||
func NewEdgeReader(provider UnitOfWorkProvider) (publicops.EdgeReader, error) {
|
||||
if isNilUnitOfWorkProvider(provider) {
|
||||
return nil, fmt.Errorf("new edge reader: unit-of-work provider must not be nil")
|
||||
}
|
||||
return &edgeReader{provider: provider}, nil
|
||||
}
|
||||
|
||||
var _ publicops.EdgeReader = (*edgeReader)(nil)
|
||||
|
||||
// ReadEdges answers one stored-edge read inside ONE unit of work, so the
|
||||
// anchor probe and the edge read see one snapshot — the property the two
|
||||
// store-backed bodies get from a shared read transaction.
|
||||
//
|
||||
// The probe is the two batched by-id reads, one per plane, rather than the
|
||||
// per-id issue-then-wisp fallback Relations uses: this role's whole reason to
|
||||
// exist is that its question is asked about many anchors at once, and a probe
|
||||
// that fanned out per id would put the round trips back that the batched edge
|
||||
// read removed.
|
||||
func (r *edgeReader) ReadEdges(ctx context.Context, request publicops.EdgeReadRequest) (publicops.EdgeReadResult, error) {
|
||||
if err := storageissueops.ValidateEdgeReadRequest(request); err != nil {
|
||||
return publicops.EdgeReadResult{}, err
|
||||
}
|
||||
anchors := storageissueops.EdgeReadAnchors(request.IDs)
|
||||
if len(anchors) == 0 {
|
||||
return publicops.EdgeReadResult{Anchors: []publicops.AnchorEdges{}}, nil
|
||||
}
|
||||
return RunTxRead(ctx, r.provider, func(ctx context.Context, uw UnitOfWork) (publicops.EdgeReadResult, error) {
|
||||
present := make(map[string]struct{}, len(anchors))
|
||||
issues, err := uw.IssueUseCase().GetIssuesByIDs(ctx, anchors)
|
||||
if err != nil {
|
||||
return publicops.EdgeReadResult{}, err
|
||||
}
|
||||
for _, issue := range issues {
|
||||
if issue != nil {
|
||||
present[issue.ID] = struct{}{}
|
||||
}
|
||||
}
|
||||
wisps, err := uw.IssueUseCase().GetWispsByIDs(ctx, anchors)
|
||||
if err != nil {
|
||||
return publicops.EdgeReadResult{}, err
|
||||
}
|
||||
for _, wisp := range wisps {
|
||||
if wisp != nil {
|
||||
present[wisp.ID] = struct{}{}
|
||||
}
|
||||
}
|
||||
edges, err := uw.DependencyUseCase().GetIssueDependencyRecords(ctx, anchors)
|
||||
if err != nil {
|
||||
return publicops.EdgeReadResult{}, err
|
||||
}
|
||||
// The type filter and the order run HERE rather than in the reads
|
||||
// above, so both implementations narrow and order through one
|
||||
// function; a filter pushed into one side's query would put the
|
||||
// narrowing in SQL on one backend and in Go on the other.
|
||||
return storageissueops.FinishEdgeRead(anchors, present, edges, request.Types), nil
|
||||
})
|
||||
}
|
||||
36
internal/telemetry/edgereader.go
Normal file
36
internal/telemetry/edgereader.go
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// EdgeReader returns the inner store's stored-edge surface wrapped in this
|
||||
// layer's instrumentation. It recurses instead of delegating: a blind
|
||||
// delegation would return the inner reader unspanned and untimed.
|
||||
func (s *InstrumentedStorage) EdgeReader() (issueops.EdgeReader, error) {
|
||||
inner, err := s.Unwrap().EdgeReader()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.WrapEdgeReader(inner), nil
|
||||
}
|
||||
|
||||
// WrapEdgeReader instruments guarded stored-edge reads with this storage
|
||||
// layer's existing telemetry meter and tracer.
|
||||
func (s *InstrumentedStorage) WrapEdgeReader(inner issueops.EdgeReader) issueops.EdgeReader {
|
||||
return &instrumentedEdgeReader{storage: s, inner: inner}
|
||||
}
|
||||
|
||||
type instrumentedEdgeReader struct {
|
||||
storage *InstrumentedStorage
|
||||
inner issueops.EdgeReader
|
||||
}
|
||||
|
||||
func (r *instrumentedEdgeReader) ReadEdges(ctx context.Context, request issueops.EdgeReadRequest) (result issueops.EdgeReadResult, err error) {
|
||||
ctx, span, started := r.storage.op(ctx, "EdgeReader.ReadEdges")
|
||||
result, err = r.inner.ReadEdges(ctx, request)
|
||||
r.storage.done(ctx, span, started, err)
|
||||
return result, err
|
||||
}
|
||||
|
|
@ -20,6 +20,7 @@ var roleAccessorNames = []string{
|
|||
"IssueLifecycle",
|
||||
"IssueReader",
|
||||
"IssueRelations",
|
||||
"EdgeReader",
|
||||
"Counter",
|
||||
"WorkspaceConfig",
|
||||
"StatsReporter",
|
||||
|
|
@ -77,7 +78,8 @@ func (s *roleAccessorStore) StatsReporter() (issueops.StatsReporter, error) {
|
|||
func (s *roleAccessorStore) CycleDetector() (issueops.CycleDetector, error) {
|
||||
return s.surface, s.err
|
||||
}
|
||||
func (s *roleAccessorStore) Commenter() (issueops.Commenter, error) { return s.surface, s.err }
|
||||
func (s *roleAccessorStore) EdgeReader() (issueops.EdgeReader, error) { return s.surface, s.err }
|
||||
func (s *roleAccessorStore) Commenter() (issueops.Commenter, error) { return s.surface, s.err }
|
||||
func (s *roleAccessorStore) ReadyClaimer() (issueops.ReadyClaimer, error) {
|
||||
return s.surface, s.err
|
||||
}
|
||||
|
|
@ -114,6 +116,9 @@ func (*roleAccessorSentinel) Get(context.Context, issueops.GetRequest) (*issueop
|
|||
func (*roleAccessorSentinel) Related(context.Context, issueops.RelatedRequest) ([]*issueops.RelatedIssue, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (*roleAccessorSentinel) ReadEdges(context.Context, issueops.EdgeReadRequest) (issueops.EdgeReadResult, error) {
|
||||
return issueops.EdgeReadResult{}, nil
|
||||
}
|
||||
func (*roleAccessorSentinel) Count(context.Context, issueops.CountRequest) (issueops.CountResult, error) {
|
||||
return issueops.CountResult{}, nil
|
||||
}
|
||||
|
|
@ -183,6 +188,7 @@ func TestInstrumentedStorageInstrumentsEveryRoleAccessor(t *testing.T) {
|
|||
{"IssueLifecycle", func() (any, error) { return wrapped.IssueLifecycle() }},
|
||||
{"IssueReader", func() (any, error) { return wrapped.IssueReader() }},
|
||||
{"IssueRelations", func() (any, error) { return wrapped.IssueRelations() }},
|
||||
{"EdgeReader", func() (any, error) { return wrapped.EdgeReader() }},
|
||||
{"Counter", func() (any, error) { return wrapped.Counter() }},
|
||||
{"WorkspaceConfig", func() (any, error) { return wrapped.WorkspaceConfig() }},
|
||||
{"StatsReporter", func() (any, error) { return wrapped.StatsReporter() }},
|
||||
|
|
@ -222,6 +228,7 @@ func TestInstrumentedStorageRoleAccessorsPropagateInnerErrors(t *testing.T) {
|
|||
{"IssueLifecycle", func() (any, error) { return wrapped.IssueLifecycle() }},
|
||||
{"IssueReader", func() (any, error) { return wrapped.IssueReader() }},
|
||||
{"IssueRelations", func() (any, error) { return wrapped.IssueRelations() }},
|
||||
{"EdgeReader", func() (any, error) { return wrapped.EdgeReader() }},
|
||||
{"Counter", func() (any, error) { return wrapped.Counter() }},
|
||||
{"WorkspaceConfig", func() (any, error) { return wrapped.WorkspaceConfig() }},
|
||||
{"StatsReporter", func() (any, error) { return wrapped.StatsReporter() }},
|
||||
|
|
|
|||
|
|
@ -286,6 +286,38 @@ func TestCycleDetectorExposesTypedUnsupportedError(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestEdgeReaderKeepsTelemetryOutermost is the stored-edge role's version of
|
||||
// TestIssueRelationsKeepsTelemetryOutermost, and it is the READ answer for the
|
||||
// same reason: reading edges fires no completion hooks, so the hook decorator
|
||||
// adds no layer and the outermost surface a caller gets is the instrumented
|
||||
// one.
|
||||
func TestEdgeReaderKeepsTelemetryOutermost(t *testing.T) {
|
||||
t.Setenv("BD_OTEL_STDOUT", "true")
|
||||
instrumented, ok := telemetry.WrapStorage(&dolt.DoltStore{}).(*telemetry.InstrumentedStorage)
|
||||
if !ok {
|
||||
t.Fatal("WrapStorage() did not create InstrumentedStorage")
|
||||
}
|
||||
|
||||
edges, err := storage.NewHookFiringStore(instrumented, nil).EdgeReader()
|
||||
if err != nil {
|
||||
t.Fatalf("EdgeReader() error = %v", err)
|
||||
}
|
||||
if got := reflect.TypeOf(edges).String(); got != "*telemetry.instrumentedEdgeReader" {
|
||||
t.Fatalf("outer layer = %s, want the telemetry wrapper unwrapped by the hook decorator", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEdgeReaderExposesTypedUnsupportedError(t *testing.T) {
|
||||
edges, err := (*dolt.DoltStore)(nil).EdgeReader()
|
||||
if edges != nil {
|
||||
t.Fatalf("EdgeReader() reader = %T, want nil", edges)
|
||||
}
|
||||
var unsupported *beads.ErrUnsupported
|
||||
if !errors.As(err, &unsupported) {
|
||||
t.Fatalf("EdgeReader() error = %v, want *beads.ErrUnsupported", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCounterExposesTypedUnsupportedError(t *testing.T) {
|
||||
counter, err := (*dolt.DoltStore)(nil).Counter()
|
||||
if counter != nil {
|
||||
|
|
|
|||
193
issueops/edgereader.go
Normal file
193
issueops/edgereader.go
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
package issueops
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// Dependency is one stored dependency edge, exactly as the database holds it:
|
||||
// a source id, a target id, a type and the edge's own annotations.
|
||||
//
|
||||
// It is the ROW and not a view of it, which is what makes this role different
|
||||
// from Relations. A target may be an "external:" reference or an id belonging
|
||||
// to ANOTHER repository — DependencyEditor accepts both — and this database
|
||||
// holds no issue for either. Relations drops such an edge, because it answers
|
||||
// with the issue on the far end and there is none. Here the edge IS the answer,
|
||||
// so it is returned with its target spelled as stored and nothing looked up.
|
||||
//
|
||||
// The ID field is EMPTY on everything this role returns. The source-keyed read
|
||||
// behind it selects the six wire columns and not the row's surrogate key (see
|
||||
// types.Dependency.ID, which says so), so a caller must not use it to tell two
|
||||
// edges apart; the (IssueID, DependsOnID, Type) triple is what identifies an
|
||||
// edge here.
|
||||
type Dependency = types.Dependency
|
||||
|
||||
// EdgeReadRequest describes one raw-edge read over several anchors at once.
|
||||
//
|
||||
// It is a BATCH request in the sense that batching is the question rather than
|
||||
// an optimization of it: `bd dep list a b c` asks what each of three named
|
||||
// issues depends on, and answers per source. Asking the same question three
|
||||
// times would give three answers a caller then has to key and merge, and would
|
||||
// cost three round trips where the storage seam offers one.
|
||||
type EdgeReadRequest struct {
|
||||
// IDs are the anchors, each an EXACT canonical id.
|
||||
//
|
||||
// EXACT is a promise this role keeps rather than an obligation it puts on
|
||||
// the caller, for the reason RelatedRequest.ID gives: a case variant, an id
|
||||
// carrying surrounding whitespace, a prefix of a real id and a real id with
|
||||
// a suffix are all misses, because an affordance that can answer ABOUT A
|
||||
// DIFFERENT ISSUE than the caller named has no place on a contract an
|
||||
// unattended client calls. A front door that wants partial-id resolution
|
||||
// resolves BEFORE it calls, which is also what lets a routed anchor be
|
||||
// resolved against the store that actually holds it.
|
||||
//
|
||||
// A miss is PER ANCHOR and is reported on that anchor rather than failing
|
||||
// the call — see AnchorEdges.Missing. That is the whole difference in miss
|
||||
// semantics between this role and Relations, which is anchored on one issue
|
||||
// and answers ErrNotFound.
|
||||
//
|
||||
// AN EMPTY ENTRY IS ErrValidation, not a ghost. The empty string names
|
||||
// nothing a caller can have meant, and reporting it as a missing anchor
|
||||
// would put a nameless row in an answer keyed by name.
|
||||
//
|
||||
// AN EMPTY SLICE IS NOT AN ERROR: it asks about no anchors and the answer
|
||||
// is no anchors, for the reason Counter answers 0 rather than refusing an
|
||||
// empty predicate. A caller looping over a list it filtered to nothing
|
||||
// should not have to special-case the empty case to avoid an error.
|
||||
//
|
||||
// REPEATS COLLAPSE. An id named twice is one anchor, at the position of its
|
||||
// first mention: the answer is keyed by anchor, and a second entry for the
|
||||
// same key carries no second fact — it would only invite a caller
|
||||
// aggregating the result to count the same edges twice.
|
||||
IDs []string
|
||||
|
||||
// Types restricts the answer to these edge types. Empty means every type.
|
||||
//
|
||||
// An entry is checked for being a value at all — non-empty, within the
|
||||
// column's length — and NEVER for membership of a known-types list, exactly
|
||||
// as RelatedRequest.Types is: the vocabulary is OPEN, so a workspace's own
|
||||
// type has to be able to filter. An unusable entry is ErrValidation rather
|
||||
// than a filter that quietly matches nothing.
|
||||
//
|
||||
// The filter narrows EDGES, never anchors. An anchor whose every edge the
|
||||
// filter rejects comes back present with no edges, which is a different
|
||||
// fact from an anchor that is not there.
|
||||
Types []DependencyType
|
||||
}
|
||||
|
||||
// AnchorEdges is one anchor's stored outgoing edges, or the report that the
|
||||
// anchor is not there.
|
||||
type AnchorEdges struct {
|
||||
// ID is the anchor, spelled exactly as the request spelled it.
|
||||
ID string
|
||||
// Edges are the anchor's stored outgoing edges — the rows whose source is
|
||||
// this anchor — after the request's type filter.
|
||||
//
|
||||
// THE ORDER IS PINNED: ascending by target id, with the edge type breaking
|
||||
// a tie. It is pinned rather than left to the query for the reason
|
||||
// Relations pins its own order: the rows come from one of two dependency
|
||||
// tables depending on which plane the anchor lives on, so the natural order
|
||||
// is an artifact of that placement — stable enough to look deliberate and
|
||||
// not stable enough to rely on.
|
||||
//
|
||||
// The tiebreaker is a TOTALITY guarantee rather than an observable one: the
|
||||
// stores hold at most one edge per (source, target) pair — a second one
|
||||
// with a different type is refused, not added — so no answer reaching a
|
||||
// caller today has two edges to break a tie between. It is stated because
|
||||
// the order must be total whatever the schema later permits, and it is
|
||||
// stated as unreachable so nobody writes a test that cannot be built.
|
||||
//
|
||||
// It is never nil for a successful call, so a caller that marshals it emits
|
||||
// an empty array rather than null.
|
||||
Edges []*Dependency
|
||||
// Missing reports that no issue and no wisp carries this id.
|
||||
//
|
||||
// It exists because an empty edge list is otherwise indistinguishable from
|
||||
// a typo, and the empty list is the COMMON case — most issues depend on
|
||||
// nothing — so the typo would never surface. That is the same reason
|
||||
// Relations probes its anchor's existence; the difference is only that a
|
||||
// batch cannot answer ErrNotFound without discarding the anchors it did
|
||||
// find.
|
||||
//
|
||||
// A missing anchor carries no edges. The converse does not hold: an anchor
|
||||
// that is present with no edges, and one whose edges the type filter
|
||||
// removed, both report false with an empty list.
|
||||
//
|
||||
// DANGLING EDGES ARE NOT MISSING ANCHORS. This flag is about the SOURCE.
|
||||
// An edge whose TARGET names nothing — an external reference, a
|
||||
// foreign-repository id, or a row left behind by a deleted issue — is
|
||||
// returned as stored, and nothing here reports on it: the target is not an
|
||||
// anchor of this request and the role does not probe it.
|
||||
Missing bool
|
||||
}
|
||||
|
||||
// EdgeReadResult is the per-anchor answer.
|
||||
type EdgeReadResult struct {
|
||||
// Anchors carries one entry per DISTINCT requested id, in the order the
|
||||
// request first named it. It is never nil for a successful call, and it is
|
||||
// a slice rather than a map because the request's order is part of the
|
||||
// answer: both front doors print the anchors in the order the caller named
|
||||
// them, and a map would have made that ordering each surface's own
|
||||
// invention.
|
||||
Anchors []AnchorEdges
|
||||
}
|
||||
|
||||
// EdgeReader describes reading STORED DEPENDENCY EDGES for several anchors at
|
||||
// once: the answer `bd dep list a b c` gives, and — like Relations — a role
|
||||
// with its own accessor. A new capability gets a new role interface and its own
|
||||
// accessor; never append a method here.
|
||||
//
|
||||
// IT IS ITS OWN ROLE RATHER THAN A SECOND Relations METHOD, and the reason is
|
||||
// worth stating because the two roles look alike from a distance. Relations is
|
||||
// SINGLE-ANCHOR and answers with HYDRATED ISSUES: its result is the issue on
|
||||
// the far end of each edge, carrying that issue's title, status and priority,
|
||||
// and an edge with no far end in this database is silently not a neighbor. It
|
||||
// answers ErrNotFound for an anchor that is not there, because with one anchor
|
||||
// there is nothing else to say. This role answers with the EDGE RECORDS
|
||||
// THEMSELVES, for MANY anchors, keyed by source, and it reports a missing
|
||||
// anchor per anchor rather than failing the call. Different answer shape,
|
||||
// different miss policy, different arity: folding them together would give one
|
||||
// role two of each, which is the accretion the governing rule exists to stop.
|
||||
//
|
||||
// IT IS ALSO NOT BlockingAnnotator. That role answers a DERIVED, best-effort
|
||||
// decoration — the open blockers and the parent of a page of issues — where
|
||||
// this one answers raw stored rows with no derivation and no policy.
|
||||
//
|
||||
// THE DIRECTION IS OUTGOING, and there is no parameter for it. The question
|
||||
// this role answers is "what does each of these depend on"; the inbound
|
||||
// direction is a different read against a different key (the batched
|
||||
// target-keyed mirror), it has its own de-duplication rule across the two
|
||||
// dependency tables, and no front door asks for it in bulk today. A role born
|
||||
// with a direction nothing sets would be a promise nothing checks — see
|
||||
// CountRequest's missing free-text field for the same decision. When something
|
||||
// needs the inbound bulk read it gets its own role, exactly as this one did.
|
||||
//
|
||||
// THE DEPENDENCY TREE IS NOT HERE EITHER, for the reason Relations gives: a
|
||||
// recursive walk has a depth, a cycle policy and a node shape of its own.
|
||||
//
|
||||
// Implementations never mutate caller-owned request values, snapshot the
|
||||
// request at method entry, and apply validation and normalization only to
|
||||
// attempt-local clones. EdgeReadRequest travels by value, so IDs and Types are
|
||||
// the members a body could otherwise write through to the caller: reading them
|
||||
// into a set is fine, sorting or de-duplicating them in place is not.
|
||||
//
|
||||
// Reading edges is a READ. Nothing here records a history entry, fires a
|
||||
// completion hook or changes a row, and a refusal changes nothing either.
|
||||
// Deterministic request-validation failures match ErrValidation; result values
|
||||
// are unspecified when error is non-nil.
|
||||
type EdgeReader interface {
|
||||
// ReadEdges returns each anchor's stored outgoing edges.
|
||||
//
|
||||
// The anchors' existence and their edges are read from ONE consistent view,
|
||||
// so an anchor cannot be reported missing by a probe that raced a create
|
||||
// the edge read then saw. That is the same promise Relations makes for its
|
||||
// single anchor, and it is the reason this is one method rather than a
|
||||
// caller's existence check followed by a caller's edge read.
|
||||
//
|
||||
// A request naming only anchors that are not there is a successful call
|
||||
// whose every entry reports Missing: there is no ErrNotFound on this role,
|
||||
// because a batch that failed for one absent id would throw away the
|
||||
// answers for the ids that were found.
|
||||
ReadEdges(ctx context.Context, req EdgeReadRequest) (EdgeReadResult, error)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue