feat(http): bd blocked over bd serve (blocked.list), plus bd blocked --flags [--raw] (#7649)
* feat(http): bd blocked over bd serve (blocked.list) through issueops.BlockedLister
`bd blocked` refused against an HTTP workspace: it called the legacy
GetBlockedIssues, which the HTTP backend stubs as unsupported. It now runs
one role on every route, and bd serve publishes that role.
- Role: issueops.BlockedLister.ListBlocked(BlockedRequest{ParentID, Labels,
LabelsAny, ExcludeLabels}) -> BlockedResult{Items}. One body,
internal/storage/issueops.ExecuteListBlockedInTx over the unchanged
GetBlockedIssuesInTx; labels normalized in the role (BlockedFilter);
Items never nil and in a total order (priority, created_at desc, id).
- Legs: DoltStore (read tx), EmbeddedDoltStore (read conn), uow (read unit
of work through the use case's GetBlockedIssues, so the
external-dependency uow decorator applies). Census: storage.DoltStorage
gains BlockedLister(); HookFiringStore passes it through (a read),
telemetry wraps it, uow.notifyingProvider, externaldeps.uowProvider and
httpapi.timedProvider build it.
- externaldeps.Store.BlockedLister is built over its own GetBlockedIssues,
so local `bd blocked` output is unchanged. Over a remote store it takes
the server's listing when the server advertises
policy.external_dependencies, else decorates the server's listing here
through EdgeReader and BatchGetter (decorateBlocked, factored out of
GetBlockedIssues).
- Wire: GET /v0/beads/blocked (listBlockedIssues; parent, label,
label_any, exclude_label) answering BlockedPage {items, has_more} with
the new x-go-type-pinned BlockedIssue schema, behind the new
blocked.list token. apigen and the wire-shape golden regenerated; the
golden diff is additive only, so wire_revision stays 2.
Config.BlockedLister is a required role, wired in bd serve.
- Client: httpclient.Store.BlockedLister dials through Store.dispatch, so
an older server is refused BEFORE the dial with *wire.CapabilityError
naming blocked.list. The legacy Store.GetBlockedIssues rides the role
(page and row cap applied to its answer) and leaves the unsupported
shell. Divergence ledger row F-blocked retired.
- CLI: `bd blocked` takes BlockedLister() from the store on the direct
routes and from the provider's BlockedListerSource on the proxied route;
runBlockedProxiedServer is deleted. --json output is the same rows in
the same order, [] when empty.
Tests: backend/conformance RunBlockedLister (10 cases: direct blocker,
child attributed to its blocked parent, closed blocker, wisp plane, pinned
status, parent filter, label filters with normalization, order, empty
slice, request not mutated) on dolt, embedded, uow and the served HTTP
client; httpapi handler tests (mapping, unknown/repeated params,
projection, capability); httpclient stub tests (pre-dial refusal naming
the token, encoding, projection, legacy door paging); skew and vocabulary
counts; TestE2E_BlockedOverHTTP (served `bd blocked --json` equals the
local command's after mapping ids and timestamps, member order included,
external blocker named, older-server refusal with no dial); corpus
gc-blocked re-marked and gc-blocked-parent added, both pending until the
reference server advertises blocked.list.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(blocked): pin server-side external decoration, refuse has_more, serve the legacy door over http
Review fixes for the blocked.list slice.
- Server-side external decoration is now pinned on the compositions bd
serve answers from. TestWrapUOWProviderBlockedListerNamesExternalBlockers
lists through the wrapped unit-of-work provider's own BlockedLister
accessor (the bd serve provider path) and requires an external-only row
and a mixed row to carry their external: refs; building that lister over
the inner provider fails it. TestServedBlockedListerCarriesExternalRefs-
WhenTheServerEnforces serves the store-shaped composition
(externaldeps.Store.BlockedLister, policy advertised) and requires the
operation's own answer, through the undecorated client role, to carry the
refs, and the client's decorated chain to return it unchanged; serving
the inner store's lister fails it.
- The client refuses an answer reporting has_more with the new typed
httpclient.TruncatedListingError instead of returning a short listing:
the operation has no cursor, and a caller reads a missing row as
unblocked. The legacy door inherits it.
- externaldeps.Store.GetBlockedIssues over an http store reads the extra
sources through the served roles (EdgeReader, BatchGetter) instead of the
raw GetIssuesByIDs / GetDependencyRecordsForIssues the http backend
refuses, and the decoration skips the source read when there is nothing
to load. The legacy door on the CLI chain (bd mol stale, the wisp
commands) now answers over http in both policy modes;
TestServedLegacyGetBlockedIssuesThroughTheDecorator pins it, paging
included. bd ready --explain still refuses on its other raw reads; the
CHANGELOG says so.
- Docs: the spec and the retired F-blocked ledger row state that the
listing is unpaged, bounded by the client's 32 MiB response limit
(refused, never read in part), and that has_more is refused.
- Contract: new cases for waits-for and conditional-blocks blockers, no
type exclusions (gate, epic), and a stale flag with no nameable blocker
(on the legs that can write the column: dolt, embedded; skipped
elsewhere with the reason). Order seeds explicit created_at values with
five rows tied on priority and created_at, two of them wisps, so only the
id tiebreak orders them; dropping the tiebreak now fails every run.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(blocked): bd blocked --flags, the blocked flag per id from stdin
`bd blocked --flags [--json]` reads ids from stdin, one per line (blank
lines and repeats ignored), and prints the blocked flag bd holds for each:
with --json, [{"id","is_blocked"}] in the order the ids were first given,
omitting an id that names no row on either plane, [] for no input. It is
the readiness column a consumer otherwise had to read with `bd sql`, so no
such consumer needs a local-only command.
It is the FLAG, not the listing: `bd blocked` narrows the stored flag to
rows it can name a blocker for, and --flags does not, so a row whose flag
is set with no nameable blocker reads true here and is absent from the
listing. Where the external-dependency policy applies, an unsatisfied
external: blocker sets the flag, as it keeps the row out of `bd ready`.
One library entry on every route: issueops.BlockedFlags over the route's
BlockingAnnotator (the store's accessor on dolt, embedded and HTTP, the
provider's on the proxied route). Over HTTP that is listBlockingAnnotations
with is_blocked behind dependencies.blocking.isBlocked; a server without
that token is refused before the dial, naming it. No wire change. The
listing's filter flags are refused with --flags rather than ignored.
Tests: TestE2E_BlockedFlagsOverHTTP (served JSON equals the local command's
after mapping ids to titles, unknown id omitted, repeat collapsed, [] on
empty stdin, filters refused; a stale-flagged row with no blocker reads
true and is absent from `bd blocked --json`, which fails if --flags is
derived from the listing; an older server's handshake refused naming the
token with no dial); TestProxiedServerBlocked/flags_reads_ids_from_stdin on
the proxied route; corpus gc-blocked-flags, pending until the reference
server advertises the token. CHANGELOG entry.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(blocked): bd blocked --flags --raw, the stored is_blocked column
`bd blocked --flags --raw [--json]` answers the stored is_blocked column
for each id read from stdin, exactly what reading is_blocked from the issues
and wisps tables returns, without the external-dependency policy: a row
blocked only by an unsatisfied external: ref reads false (the policy-aware
--flags reads true), and a stale flag reads true either way. Same output
shape as --flags. This lets a consumer move off a `bd sql` read of the
column with no change in what it reads. The default --flags is unchanged.
The role is taken from beneath every decorator: storage.UnwrapStore on the
direct routes, uow.UnwrapProvider on the proxied route. Over HTTP the
innermost store is the http client, whose annotation read is the server's
answer: against a server that does not advertise
policy.external_dependencies that answer is the column, and --raw is
served. A server that advertises it decorates the flag it answers, the v0
wire has no member asking it for the column, and the decorated flag cannot
be turned back into the column client-side, so --raw against such a server
is refused before the annotation read, naming the token, rather than
answered with the decorated flag. --raw without --flags is refused.
Tests: TestE2E_BlockedFlagsOverHTTP/raw_is_the_stored_column (served --raw
equals local --raw; the externally-blocked-only row reads true with --flags
and false with --raw on both; locally blocked rows agree; a stale-flagged
row reads true in both modes; --raw without --flags exits 1; a server
advertising the policy refuses --raw with no annotation request);
TestProxiedServerBlocked/flags_raw_is_the_stored_column; corpus
gc-blocked-flags-raw (pending until the reference server advertises
dependencies.blocking.isBlocked). Routing --raw through the decorated
annotator fails the e2e. CHANGELOG entry.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(changelog): bd blocked --flags --raw is for the local and proxied routes
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(blocked): give the e2e gate-kid its own priority; document --flags answers closed ids
TestE2E_BlockedOverHTTP seeded gate-parent and gate-kid at one priority, so
when both landed in the same second their order fell to the generated ids,
which differ between the local and the served workspace: the comparison
failed intermittently. gate-kid now has its own priority. Ten runs on the
embedded lane pass.
bd blocked --flags answers a closed id too, with its stored flag; a SQL read
of the column filtered on status <> 'closed' leaves it out. Said in the
command's doc and the CHANGELOG.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(blocked): apply label filters to external-only blocked rows
The external-dependency policy appends a row blocked only by an
unsatisfied external: ref after the label query has run, so --label,
--label-any and --exclude-label never judged it: bd blocked and
GET /v0/beads/blocked listed it whatever its labels, on every route.
Both decorators now filter those rows by the request's labels. The uow
decorator reads them through GetMany, chunked at MaxGetManyIDs, so their
labels are hydrated; GetIssuesByIDs left them empty, which also printed
them unlabelled on the proxied route.
Review fixes (adopt-pr apply-fixes, iteration 1):
- major #1: label filters on external-only rows in the store and uow
decorators, with absence-asserting arms in the unit, served httpclient
(server- and client-enforced policy), e2e and proxied tiers; the spec
and the role doc say such rows are narrowed like every other row.
- minor #2: the policy.external_dependencies token prose names the
blocked listing (spec, routes.go, regenerated types.gen.go).
- minor #6: SERVE_RUNBOOK and the allowUnlimited comment record the
blocked listing's unbounded whole-set answer and why.
- minor #10: BlockedLister telemetry-outermost and typed-unsupported pins
beside the ReadyCounter pair, plus the externaldeps wrap pin.
- nit #9: F-blocked names --flags --raw's refusal against a server that
applies the policy (ledger.go and the regenerated ledger doc).
- nit #11: the remote BlockedLister no longer builds a local lister it
then discards.
Review fixes (adopt-pr apply-fixes, iteration 2; the review approved at
940 with one minor and two nits, none gating):
- minor (the --flags refusal list was unpinned): the new
TestBlockedFlagsRefusesEveryListingFilter pins blockedFlagFilterFlags
to the flags blockedCmd registers, in both directions. Every
registered flag except --flags and --raw must be refused, and every
entry must name a registered flag. The test walks Flags() rather than
LocalFlags(), so it does not merge the root's persistent flags into
blockedCmd, and it skips inherited root flags and cobra's --help.
Mutants:
- four fail it: a new filter flag left off the list, a dropped
entry, a misspelled entry, and --raw added to the list;
- a simulated earlier in-process run (merged root flags plus --help)
stays green, and fails once either skip is removed.
- nit (the remote branch's span): the remote BlockedLister comment now
says why that lister is not wrapped again. The inner lister already
carries telemetry's span, so wrapping would nest a second span of the
same name. The comment also says what runs outside that span.
- nit (duplicated order comparator): left as is. finishBlockedIssues
predates this PR, so merging the two sorts would refactor existing
code with no review pass left after this one.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
This commit is contained in:
parent
601be8a6bf
commit
4450fe99bb
81 changed files with 4084 additions and 146 deletions
|
|
@ -176,6 +176,7 @@
|
|||
40 3 TestTransactionCleanupBeforeSQLCommitRemainsDefinite
|
||||
40 3 TestUnknownProvenanceLeaseStaysReclaimable
|
||||
|
||||
40 4 TestBlockedListerContract
|
||||
40 4 TestCreateBatchFastPathsMatchPerRowSmallDepAdd_Embedded
|
||||
40 4 TestEmbeddedIssueOperationsUpdateLabelPatchOrdering
|
||||
40 4 TestEmbeddedReaderGetMissIsNotFoundAndBackendFailureDoesNotDecay
|
||||
|
|
|
|||
56
CHANGELOG.md
56
CHANGELOG.md
|
|
@ -9,6 +9,56 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
|
||||
### Added
|
||||
|
||||
- `bd blocked --flags` prints the blocked flag for each id read from stdin
|
||||
(one per line; blank lines and repeats ignored), with `--json` as
|
||||
`[{"id","is_blocked"}]` in the order the ids were given, omitting an id that
|
||||
names no row on either plane. A closed id is answered too, with its stored
|
||||
flag (a `status <> 'closed'` SQL read of the column leaves it out). It is the flag `bd ready` filters on, not the
|
||||
listing: a row whose stored flag is set with no nameable blocker reads true
|
||||
here and is absent from `bd blocked`. It runs `issueops.BlockedFlags` on
|
||||
every route; over HTTP that is `listBlockingAnnotations` with `is_blocked`,
|
||||
behind `dependencies.blocking.isBlocked`, refused before the dial against a
|
||||
server that does not advertise it. The listing's filter flags are refused
|
||||
with `--flags`.
|
||||
- `bd blocked --flags --raw` answers the stored `is_blocked` column itself,
|
||||
without the external-dependency policy: a row blocked only by an
|
||||
unsatisfied `external:` ref reads `false` (the policy-aware `--flags`
|
||||
reads `true`); a stale flag reads `true` either way. `--raw` is for the
|
||||
local and proxied routes, where it reads the column directly and the two
|
||||
answer the same. Over HTTP it is answered only by a server that does not
|
||||
advertise `policy.external_dependencies` (whose flag is the column); a
|
||||
server advertising it answers only the policy-aware flag, so `--raw`
|
||||
against it is refused before the dial rather than answered with the
|
||||
decorated flag. `--raw` without `--flags` is refused.
|
||||
- `bd blocked` works over a connected HTTP workspace. The blocked listing is
|
||||
a role, `issueops.BlockedLister` (`ListBlocked(BlockedRequest{ParentID,
|
||||
Labels, LabelsAny, ExcludeLabels}) -> BlockedResult{Items}`), on every
|
||||
backend leg over the same body `GetBlockedIssues` runs, and `bd serve`
|
||||
publishes it as `GET /v0/beads/blocked` (`parent`, and the repeatable
|
||||
`label`, `label_any` and `exclude_label`), answering `{items, has_more}`
|
||||
with `BlockedIssue` rows (the element `bd blocked --json` prints), behind
|
||||
the new `blocked.list` capability token (additive; no wire_revision bump).
|
||||
The listing names unsatisfied `external:` blockers wherever the
|
||||
external-dependency policy applies: on the server when it advertises
|
||||
`policy.external_dependencies`, else on the client, as every other policy
|
||||
read does. The HTTP backend's `BlockedLister()` and legacy
|
||||
`GetBlockedIssues` dial it; against a server that does not advertise the
|
||||
token they refuse before dialing with a typed capability error naming
|
||||
`blocked.list`, and never compose the listing from other reads. The
|
||||
listing is unpaged: a server answer that reports `has_more` is refused
|
||||
with the new `httpclient.TruncatedListingError` rather than returned
|
||||
short, and an answer over the client's 32 MiB response limit is refused
|
||||
as any oversized response is. The external-dependency decorator's legacy
|
||||
`GetBlockedIssues` over an HTTP store now reads the extra sources through
|
||||
the served roles (it failed on a raw multi-id read before), so callers of
|
||||
that door no longer fail on it; commands that also make other raw reads
|
||||
the HTTP backend does not serve (`bd ready --explain`) still refuse on
|
||||
those. `bd
|
||||
blocked` runs the role on every route (the proxied-server route through
|
||||
the provider's accessor) with unchanged output: `--json` prints the same
|
||||
rows in the same order (priority, then newest first, then id, which now
|
||||
also breaks a tie the order used to leave to chance), and `[]`, never
|
||||
`null`, when nothing is blocked.
|
||||
- `bd list`'s remaining filters work over a connected HTTP workspace.
|
||||
`GET /v0/beads/issues` accepts `updated_after`/`updated_before`,
|
||||
`closed_after`/`closed_before`, `defer_after`/`defer_before`,
|
||||
|
|
@ -678,6 +728,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
|
||||
### Fixed
|
||||
|
||||
- **`bd blocked --label`, `--label-any` and `--exclude-label` apply to a row
|
||||
blocked only by an unsatisfied `external:` dependency.** The
|
||||
external-dependency policy lists such a row itself, after the label query
|
||||
has run, and it was listed whatever its labels; it is now narrowed by the
|
||||
label filters like every other row, on every route. On the proxied-server
|
||||
route such a row also printed with no labels; it now prints them.
|
||||
- **`bd gate add-waiter` survives contention the store gave up replaying.**
|
||||
It retried only a version miss, so a convoy adder failed when its guarded
|
||||
write ended in a serialization failure or deadlock the backend stopped
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ go_library(
|
|||
"batch_closer_contract.go",
|
||||
"batch_creator_contract.go",
|
||||
"batch_getter_contract.go",
|
||||
"blocked_lister_contract.go",
|
||||
"blocked_state.go",
|
||||
"blocking_annotator_contract.go",
|
||||
"bootstrapper_contract.go",
|
||||
|
|
|
|||
426
backend/conformance/blocked_lister_contract.go
Normal file
426
backend/conformance/blocked_lister_contract.go
Normal file
|
|
@ -0,0 +1,426 @@
|
|||
package conformance
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// This file holds the semantic contract every implementation of
|
||||
// publicops.BlockedLister must satisfy: what issueops/blockedlister.go
|
||||
// promises, asserted on every leg (dolt, embedded dolt, unit of work, and the
|
||||
// served HTTP client) so `bd blocked` answers one listing whichever route it
|
||||
// takes.
|
||||
//
|
||||
// EVERY CASE IS SCOPED BY A LABEL: the blocked set is a property of the whole
|
||||
// database, not of an id prefix, so a row seeded by one case is inside the
|
||||
// next one's answer unless each asks through Labels.
|
||||
|
||||
// BlockedListerFixture supplies adapter-specific storage access for the
|
||||
// blocked-listing assertions.
|
||||
type BlockedListerFixture struct {
|
||||
// IssuePrefix namespaces the ids each case seeds, so several cases can
|
||||
// share one database.
|
||||
IssuePrefix string
|
||||
// BlockedLister is the surface under test.
|
||||
BlockedLister publicops.BlockedLister
|
||||
// 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.
|
||||
CreateWisp func(context.Context, *types.Issue, string) error
|
||||
// AddDependency seeds ONE edge, recomputing the stored blocked flag the
|
||||
// way every dependency write does.
|
||||
AddDependency func(context.Context, *types.Dependency, string) error
|
||||
// MarkBlocked sets the stored is_blocked flag on one durable issue
|
||||
// directly, without the edge that would justify it: the stale flag `bd
|
||||
// recompute-blocked` exists to repair. It must fail unless exactly one row
|
||||
// changed. A nil hook means this leg cannot write the column, and the case
|
||||
// that needs it skips with that reason.
|
||||
MarkBlocked func(context.Context, string) error
|
||||
}
|
||||
|
||||
// RunBlockedLister runs every blocked-listing case as a subtest of t.
|
||||
func RunBlockedLister(t *testing.T, ctx context.Context, fixture BlockedListerFixture) {
|
||||
t.Helper()
|
||||
t.Run("NamesADirectBlocker", func(t *testing.T) { runBlockedNamesADirectBlocker(t, ctx, fixture) })
|
||||
t.Run("AttributesAChildToItsBlockedParent", func(t *testing.T) { runBlockedAttributesAChildToItsParent(t, ctx, fixture) })
|
||||
t.Run("ClosedBlockerDoesNotBlock", func(t *testing.T) { runBlockedClosedBlockerDoesNotBlock(t, ctx, fixture) })
|
||||
t.Run("IncludesTheWispPlane", func(t *testing.T) { runBlockedIncludesTheWispPlane(t, ctx, fixture) })
|
||||
t.Run("ExcludesThePinnedStatus", func(t *testing.T) { runBlockedExcludesThePinnedStatus(t, ctx, fixture) })
|
||||
t.Run("ParentFilter", func(t *testing.T) { runBlockedParentFilter(t, ctx, fixture) })
|
||||
t.Run("LabelFilters", func(t *testing.T) { runBlockedLabelFilters(t, ctx, fixture) })
|
||||
t.Run("Order", func(t *testing.T) { runBlockedOrder(t, ctx, fixture) })
|
||||
t.Run("NamesWaitsForAndConditionalBlockers", func(t *testing.T) { runBlockedNamesWaitsForAndConditionalBlockers(t, ctx, fixture) })
|
||||
t.Run("OmitsAStaleFlagWithNoNameableBlocker", func(t *testing.T) { runBlockedOmitsAStaleFlag(t, ctx, fixture) })
|
||||
t.Run("HasNoTypeExclusions", func(t *testing.T) { runBlockedHasNoTypeExclusions(t, ctx, fixture) })
|
||||
t.Run("EmptyIsAnEmptySlice", func(t *testing.T) { runBlockedEmptyIsAnEmptySlice(t, ctx, fixture) })
|
||||
t.Run("DoesNotMutateTheCallerRequest", func(t *testing.T) { runBlockedDoesNotMutateTheRequest(t, ctx, fixture) })
|
||||
}
|
||||
|
||||
// runBlockedNamesADirectBlocker: an issue with an open `blocks` target is
|
||||
// listed with that target as its one blocker; the target itself is not.
|
||||
func runBlockedNamesADirectBlocker(t *testing.T, ctx context.Context, f BlockedListerFixture) {
|
||||
label := f.IssuePrefix + "-bl-direct"
|
||||
blocked, blocker := blListerID(f, "direct-src"), blListerID(f, "direct-dst")
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(blocked, 1, label))
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(blocker, 1, label))
|
||||
blListerSeedEdge(t, ctx, f, blocked, blocker, types.DepBlocks)
|
||||
|
||||
items := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}})
|
||||
blListerAssertRows(t, items, map[string][]string{blocked: {blocker}})
|
||||
}
|
||||
|
||||
// runBlockedAttributesAChildToItsParent: a child of a blocked parent, with no
|
||||
// blocker of its own, is listed with its parent named as the blocker.
|
||||
func runBlockedAttributesAChildToItsParent(t *testing.T, ctx context.Context, f BlockedListerFixture) {
|
||||
label := f.IssuePrefix + "-bl-child"
|
||||
parent, child, blocker := blListerID(f, "child-parent"), blListerID(f, "child-child"), blListerID(f, "child-blocker")
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(parent, 1, label))
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(blocker, 1, label+"-other"))
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(child, 1, label))
|
||||
blListerSeedEdge(t, ctx, f, child, parent, types.DepParentChild)
|
||||
blListerSeedEdge(t, ctx, f, parent, blocker, types.DepBlocks)
|
||||
|
||||
items := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}})
|
||||
blListerAssertRows(t, items, map[string][]string{parent: {blocker}, child: {parent}})
|
||||
}
|
||||
|
||||
// runBlockedClosedBlockerDoesNotBlock: a `blocks` edge onto a closed target
|
||||
// names no blocker, so the source is not listed.
|
||||
func runBlockedClosedBlockerDoesNotBlock(t *testing.T, ctx context.Context, f BlockedListerFixture) {
|
||||
label := f.IssuePrefix + "-bl-closed"
|
||||
src, dst := blListerID(f, "closed-src"), blListerID(f, "closed-dst")
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(src, 1, label))
|
||||
closed := blListerIssue(dst, 1, label)
|
||||
closed.Status = types.StatusClosed
|
||||
blListerSeedIssue(t, ctx, f, closed)
|
||||
blListerSeedEdge(t, ctx, f, src, dst, types.DepBlocks)
|
||||
|
||||
items := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}})
|
||||
blListerAssertRows(t, items, map[string][]string{})
|
||||
}
|
||||
|
||||
// runBlockedIncludesTheWispPlane: a blocked wisp is listed beside the issues.
|
||||
func runBlockedIncludesTheWispPlane(t *testing.T, ctx context.Context, f BlockedListerFixture) {
|
||||
label := f.IssuePrefix + "-bl-wisp"
|
||||
wisp, blocker := blListerID(f, "wisp-src"), blListerID(f, "wisp-dst")
|
||||
w := blListerIssue(wisp, 1, label)
|
||||
w.Ephemeral = true
|
||||
if err := f.CreateWisp(ctx, w, "seed"); err != nil {
|
||||
t.Fatalf("seed wisp %s: %v", wisp, err)
|
||||
}
|
||||
b := blListerIssue(blocker, 1, label)
|
||||
b.Ephemeral = true
|
||||
if err := f.CreateWisp(ctx, b, "seed"); err != nil {
|
||||
t.Fatalf("seed wisp %s: %v", blocker, err)
|
||||
}
|
||||
blListerSeedEdge(t, ctx, f, wisp, blocker, types.DepBlocks)
|
||||
|
||||
items := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}})
|
||||
blListerAssertRows(t, items, map[string][]string{wisp: {blocker}})
|
||||
}
|
||||
|
||||
// runBlockedExcludesThePinnedStatus: a row whose status is pinned is never
|
||||
// listed, whatever blocks it.
|
||||
func runBlockedExcludesThePinnedStatus(t *testing.T, ctx context.Context, f BlockedListerFixture) {
|
||||
label := f.IssuePrefix + "-bl-pinned"
|
||||
pinned, open, blocker := blListerID(f, "pinned-src"), blListerID(f, "pinned-open"), blListerID(f, "pinned-dst")
|
||||
p := blListerIssue(pinned, 1, label)
|
||||
p.Status = types.StatusPinned
|
||||
blListerSeedIssue(t, ctx, f, p)
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(open, 1, label))
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(blocker, 1, label+"-other"))
|
||||
blListerSeedEdge(t, ctx, f, pinned, blocker, types.DepBlocks)
|
||||
blListerSeedEdge(t, ctx, f, open, blocker, types.DepBlocks)
|
||||
|
||||
items := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}})
|
||||
blListerAssertRows(t, items, map[string][]string{open: {blocker}})
|
||||
}
|
||||
|
||||
// runBlockedParentFilter: ParentID narrows to the parent's direct children.
|
||||
func runBlockedParentFilter(t *testing.T, ctx context.Context, f BlockedListerFixture) {
|
||||
label := f.IssuePrefix + "-bl-parent"
|
||||
parent, kid, stranger, blocker := blListerID(f, "pf-parent"), blListerID(f, "pf-kid"), blListerID(f, "pf-stranger"), blListerID(f, "pf-blocker")
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(parent, 1, label+"-other"))
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(blocker, 1, label+"-other"))
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(kid, 1, label))
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(stranger, 1, label))
|
||||
blListerSeedEdge(t, ctx, f, kid, parent, types.DepParentChild)
|
||||
blListerSeedEdge(t, ctx, f, kid, blocker, types.DepBlocks)
|
||||
blListerSeedEdge(t, ctx, f, stranger, blocker, types.DepBlocks)
|
||||
|
||||
all := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}})
|
||||
blListerAssertRows(t, all, map[string][]string{kid: {blocker}, stranger: {blocker}})
|
||||
narrowed := blListerList(t, ctx, f, publicops.BlockedRequest{ParentID: parent, Labels: []string{label}})
|
||||
blListerAssertRows(t, narrowed, map[string][]string{kid: {blocker}})
|
||||
}
|
||||
|
||||
// runBlockedLabelFilters: Labels is AND, LabelsAny is OR, ExcludeLabels
|
||||
// removes, and every value is trimmed with blanks dropped.
|
||||
func runBlockedLabelFilters(t *testing.T, ctx context.Context, f BlockedListerFixture) {
|
||||
base := f.IssuePrefix + "-bl-lab"
|
||||
red, blue := base+"-red", base+"-blue"
|
||||
both, onlyRed, onlyBlue, blocker := blListerID(f, "lab-both"), blListerID(f, "lab-red"), blListerID(f, "lab-blue"), blListerID(f, "lab-blocker")
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(both, 1, base, red, blue))
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(onlyRed, 1, base, red))
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(onlyBlue, 1, base, blue))
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(blocker, 1, base+"-other"))
|
||||
for _, id := range []string{both, onlyRed, onlyBlue} {
|
||||
blListerSeedEdge(t, ctx, f, id, blocker, types.DepBlocks)
|
||||
}
|
||||
want := func(ids ...string) map[string][]string {
|
||||
m := map[string][]string{}
|
||||
for _, id := range ids {
|
||||
m[id] = []string{blocker}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
blListerAssertRows(t, blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{" " + red + " ", "", blue}}), want(both))
|
||||
blListerAssertRows(t, blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{base}, LabelsAny: []string{red, blue}}), want(both, onlyRed, onlyBlue))
|
||||
blListerAssertRows(t, blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{base}, ExcludeLabels: []string{" " + blue}}), want(onlyRed))
|
||||
}
|
||||
|
||||
// runBlockedOrder: priority ascending, then created_at descending, then id.
|
||||
//
|
||||
// The created_at values are seeded explicitly, so every key decides at least
|
||||
// one pair: two rows share a priority and differ in created_at (newest first),
|
||||
// and five share both priority and created_at (the id breaks the tie). The
|
||||
// expected order is written out rather than recomputed from the answer.
|
||||
func runBlockedOrder(t *testing.T, ctx context.Context, f BlockedListerFixture) {
|
||||
label := f.IssuePrefix + "-bl-order"
|
||||
blocker := blListerID(f, "order-blocker")
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(blocker, 1, label+"-other"))
|
||||
older := time.Date(2026, 1, 1, 10, 0, 0, 0, time.UTC)
|
||||
newer := older.Add(time.Hour)
|
||||
// Two of the five tied rows are wisps. The store body assembles rows
|
||||
// issues-plane first, each plane in id order, so the ids alone would put
|
||||
// the tied run in the wrong order (b, d, e, then a, c); only the id
|
||||
// tiebreak puts it right.
|
||||
rows := []struct {
|
||||
name string
|
||||
priority int
|
||||
created time.Time
|
||||
wisp bool
|
||||
}{
|
||||
{"order-p3", 3, newer, false},
|
||||
{"order-p0-older", 0, older, false},
|
||||
{"order-p0-newer-e", 0, newer, false},
|
||||
{"order-p0-newer-c", 0, newer, true},
|
||||
{"order-p0-newer-a", 0, newer, true},
|
||||
{"order-p0-newer-d", 0, newer, false},
|
||||
{"order-p0-newer-b", 0, newer, false},
|
||||
{"order-p1", 1, older, false},
|
||||
}
|
||||
for _, row := range rows {
|
||||
issue := blListerIssue(blListerID(f, row.name), row.priority, label)
|
||||
issue.CreatedAt = row.created
|
||||
issue.UpdatedAt = row.created
|
||||
if row.wisp {
|
||||
issue.Ephemeral = true
|
||||
if err := f.CreateWisp(ctx, issue, "seed"); err != nil {
|
||||
t.Fatalf("seed wisp %s: %v", issue.ID, err)
|
||||
}
|
||||
} else {
|
||||
blListerSeedIssue(t, ctx, f, issue)
|
||||
}
|
||||
blListerSeedEdge(t, ctx, f, issue.ID, blocker, types.DepBlocks)
|
||||
}
|
||||
want := []string{
|
||||
blListerID(f, "order-p0-newer-a"),
|
||||
blListerID(f, "order-p0-newer-b"),
|
||||
blListerID(f, "order-p0-newer-c"),
|
||||
blListerID(f, "order-p0-newer-d"),
|
||||
blListerID(f, "order-p0-newer-e"),
|
||||
blListerID(f, "order-p0-older"),
|
||||
blListerID(f, "order-p1"),
|
||||
blListerID(f, "order-p3"),
|
||||
}
|
||||
got := blListerIDs(blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}}))
|
||||
if !slices.Equal(got, want) {
|
||||
t.Errorf("listing order = %v, want %v (priority ascending, created_at descending, id)", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// runBlockedNamesWaitsForAndConditionalBlockers: a waits-for onto a spawner
|
||||
// whose child is still open, and a conditional-blocks onto an open target,
|
||||
// each name their target, as a blocks edge does.
|
||||
func runBlockedNamesWaitsForAndConditionalBlockers(t *testing.T, ctx context.Context, f BlockedListerFixture) {
|
||||
label := f.IssuePrefix + "-bl-wf"
|
||||
spawner, spawned := blListerID(f, "wf-spawner"), blListerID(f, "wf-spawned")
|
||||
waiter := blListerID(f, "wf-waiter")
|
||||
target, conditional := blListerID(f, "cb-target"), blListerID(f, "cb-src")
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(spawner, 1, label+"-other"))
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(spawned, 1, label+"-other"))
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(target, 1, label+"-other"))
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(waiter, 1, label))
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(conditional, 1, label))
|
||||
blListerSeedEdge(t, ctx, f, spawned, spawner, types.DepParentChild)
|
||||
blListerSeedEdge(t, ctx, f, waiter, spawner, types.DepWaitsFor)
|
||||
blListerSeedEdge(t, ctx, f, conditional, target, types.DepConditionalBlocks)
|
||||
|
||||
items := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}})
|
||||
blListerAssertRows(t, items, map[string][]string{waiter: {spawner}, conditional: {target}})
|
||||
}
|
||||
|
||||
// runBlockedOmitsAStaleFlag: a row whose stored flag says blocked but which
|
||||
// has no active blocker and no parent names no blocker, so it is not listed.
|
||||
// This is the narrowing gc's readiness projection documents relying on.
|
||||
func runBlockedOmitsAStaleFlag(t *testing.T, ctx context.Context, f BlockedListerFixture) {
|
||||
if f.MarkBlocked == nil {
|
||||
t.Skip("this leg cannot write the stored is_blocked flag directly")
|
||||
}
|
||||
label := f.IssuePrefix + "-bl-stale"
|
||||
stale, real, blocker := blListerID(f, "stale-src"), blListerID(f, "stale-real"), blListerID(f, "stale-blocker")
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(stale, 1, label))
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(real, 1, label))
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(blocker, 1, label+"-other"))
|
||||
blListerSeedEdge(t, ctx, f, real, blocker, types.DepBlocks)
|
||||
if err := f.MarkBlocked(ctx, stale); err != nil {
|
||||
t.Fatalf("mark %s blocked: %v", stale, err)
|
||||
}
|
||||
|
||||
items := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}})
|
||||
blListerAssertRows(t, items, map[string][]string{real: {blocker}})
|
||||
}
|
||||
|
||||
// runBlockedHasNoTypeExclusions: a gate is listed like any other row; the
|
||||
// blocked door excludes no issue type (unlike the ready front).
|
||||
func runBlockedHasNoTypeExclusions(t *testing.T, ctx context.Context, f BlockedListerFixture) {
|
||||
label := f.IssuePrefix + "-bl-type"
|
||||
gate, epic, blocker := blListerID(f, "type-gate"), blListerID(f, "type-epic"), blListerID(f, "type-blocker")
|
||||
g := blListerIssue(gate, 1, label)
|
||||
g.IssueType = types.TypeGate
|
||||
g.AwaitType = "human"
|
||||
blListerSeedIssue(t, ctx, f, g)
|
||||
e := blListerIssue(epic, 1, label)
|
||||
e.IssueType = types.TypeEpic
|
||||
blListerSeedIssue(t, ctx, f, e)
|
||||
blListerSeedIssue(t, ctx, f, blListerIssue(blocker, 1, label+"-other"))
|
||||
blListerSeedEdge(t, ctx, f, gate, blocker, types.DepBlocks)
|
||||
blListerSeedEdge(t, ctx, f, epic, blocker, types.DepBlocks)
|
||||
|
||||
items := blListerList(t, ctx, f, publicops.BlockedRequest{Labels: []string{label}})
|
||||
blListerAssertRows(t, items, map[string][]string{gate: {blocker}, epic: {blocker}})
|
||||
}
|
||||
|
||||
// runBlockedEmptyIsAnEmptySlice: nothing blocked is an empty, non-nil slice
|
||||
// and a nil error.
|
||||
func runBlockedEmptyIsAnEmptySlice(t *testing.T, ctx context.Context, f BlockedListerFixture) {
|
||||
result, err := f.BlockedLister.ListBlocked(ctx, publicops.BlockedRequest{Labels: []string{f.IssuePrefix + "-bl-nothing"}})
|
||||
if err != nil {
|
||||
t.Fatalf("ListBlocked: %v", err)
|
||||
}
|
||||
if result.Items == nil || len(result.Items) != 0 {
|
||||
t.Fatalf("Items = %#v, want an empty non-nil slice", result.Items)
|
||||
}
|
||||
}
|
||||
|
||||
// runBlockedDoesNotMutateTheRequest: the caller's label slices come back as
|
||||
// they were sent, normalization notwithstanding.
|
||||
func runBlockedDoesNotMutateTheRequest(t *testing.T, ctx context.Context, f BlockedListerFixture) {
|
||||
req := publicops.BlockedRequest{
|
||||
ParentID: " ",
|
||||
Labels: []string{" a ", "", "a"},
|
||||
LabelsAny: []string{" b"},
|
||||
ExcludeLabels: []string{"c "},
|
||||
}
|
||||
before := publicops.BlockedRequest{
|
||||
ParentID: req.ParentID,
|
||||
Labels: slices.Clone(req.Labels),
|
||||
LabelsAny: slices.Clone(req.LabelsAny),
|
||||
ExcludeLabels: slices.Clone(req.ExcludeLabels),
|
||||
}
|
||||
if _, err := f.BlockedLister.ListBlocked(ctx, req); err != nil {
|
||||
t.Fatalf("ListBlocked: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(req, before) {
|
||||
t.Errorf("request after = %#v, before = %#v", req, before)
|
||||
}
|
||||
}
|
||||
|
||||
func blListerID(f BlockedListerFixture, name string) string {
|
||||
return fmt.Sprintf("%s-%s", f.IssuePrefix, name)
|
||||
}
|
||||
|
||||
func blListerIssue(id string, priority int, labels ...string) *types.Issue {
|
||||
return &types.Issue{
|
||||
ID: id,
|
||||
Title: id,
|
||||
Status: types.StatusOpen,
|
||||
Priority: priority,
|
||||
IssueType: types.TypeTask,
|
||||
Labels: labels,
|
||||
}
|
||||
}
|
||||
|
||||
func blListerSeedIssue(t *testing.T, ctx context.Context, f BlockedListerFixture, issue *types.Issue) {
|
||||
t.Helper()
|
||||
if err := f.CreateIssue(ctx, issue, "seed"); err != nil {
|
||||
t.Fatalf("seed issue %s: %v", issue.ID, err)
|
||||
}
|
||||
}
|
||||
|
||||
func blListerSeedEdge(t *testing.T, ctx context.Context, f BlockedListerFixture, from, to string, kind types.DependencyType) {
|
||||
t.Helper()
|
||||
if err := f.AddDependency(ctx, &types.Dependency{IssueID: from, DependsOnID: to, Type: kind}, "seed"); err != nil {
|
||||
t.Fatalf("seed %s edge %s -> %s: %v", kind, from, to, err)
|
||||
}
|
||||
}
|
||||
|
||||
func blListerList(t *testing.T, ctx context.Context, f BlockedListerFixture, req publicops.BlockedRequest) []*types.BlockedIssue {
|
||||
t.Helper()
|
||||
result, err := f.BlockedLister.ListBlocked(ctx, req)
|
||||
if err != nil {
|
||||
t.Fatalf("ListBlocked(%+v): %v", req, err)
|
||||
}
|
||||
if result.Items == nil {
|
||||
t.Fatalf("ListBlocked(%+v) Items is nil; the role promises a non-nil slice", req)
|
||||
}
|
||||
return result.Items
|
||||
}
|
||||
|
||||
func blListerIDs(items []*types.BlockedIssue) []string {
|
||||
ids := make([]string, 0, len(items))
|
||||
for _, item := range items {
|
||||
ids = append(ids, item.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// assertBlockedRows requires the listing to be exactly want: the same ids,
|
||||
// each naming exactly the blockers want gives it (in any order), with
|
||||
// BlockedByCount equal to their number.
|
||||
func blListerAssertRows(t *testing.T, items []*types.BlockedIssue, want map[string][]string) {
|
||||
t.Helper()
|
||||
got := map[string][]string{}
|
||||
for _, item := range items {
|
||||
if item == nil {
|
||||
t.Fatalf("listing carries a nil row")
|
||||
}
|
||||
if _, dup := got[item.ID]; dup {
|
||||
t.Errorf("row %s listed twice", item.ID)
|
||||
}
|
||||
blockers := slices.Clone(item.BlockedBy)
|
||||
slices.Sort(blockers)
|
||||
got[item.ID] = blockers
|
||||
if item.BlockedByCount != len(item.BlockedBy) {
|
||||
t.Errorf("row %s: BlockedByCount = %d, len(BlockedBy) = %d", item.ID, item.BlockedByCount, len(item.BlockedBy))
|
||||
}
|
||||
}
|
||||
normalized := map[string][]string{}
|
||||
for id, blockers := range want {
|
||||
b := slices.Clone(blockers)
|
||||
slices.Sort(b)
|
||||
normalized[id] = b
|
||||
}
|
||||
if !reflect.DeepEqual(got, normalized) {
|
||||
t.Errorf("listing = %v, want %v", got, normalized)
|
||||
}
|
||||
}
|
||||
|
|
@ -31,6 +31,8 @@ go_test(
|
|||
timeout = "long",
|
||||
srcs = [
|
||||
"attach_test.go",
|
||||
"e2e_blocked_flags_test.go",
|
||||
"e2e_blocked_test.go",
|
||||
"e2e_cli_test.go",
|
||||
"e2e_export_test.go",
|
||||
"e2e_gates_test.go",
|
||||
|
|
|
|||
|
|
@ -144,6 +144,8 @@ func corpusServeConfig(t *testing.T, s storage.DoltStorage) httpapi.Config {
|
|||
must("LeaseReclaimer")
|
||||
cfg.Heartbeater, err = s.Heartbeater()
|
||||
must("Heartbeater")
|
||||
cfg.BlockedLister, err = s.BlockedLister()
|
||||
must("BlockedLister")
|
||||
cfg.Relations, err = s.IssueRelations()
|
||||
must("IssueRelations")
|
||||
cfg.Commenter, err = s.Commenter()
|
||||
|
|
|
|||
18
backend/http/corpus/testdata/corpus.yaml
vendored
18
backend/http/corpus/testdata/corpus.yaml
vendored
|
|
@ -404,7 +404,23 @@ shapes:
|
|||
- id: gc-blocked
|
||||
source: gc bdstore_ready_projection.go fetchReadyProjectionViaBlocked
|
||||
args: [blocked, --json]
|
||||
pending: {slice: "S18", reason: "bd blocked hits the GetBlockedIssues stub (B3 #10)"}
|
||||
pending: {slice: "SRV-1", reason: "bd blocked dials listBlockedIssues behind blocked.list, which the reference server does not advertise, so the client refuses at its capability preflight (pinned passing against the current server by backend/http TestE2E_BlockedOverHTTP); remove the mark when reference_server.json is upgraded"}
|
||||
- id: gc-blocked-flags
|
||||
source: gc bdstore_ready_projection.go readiness door (bd blocked --flags --json, ids on stdin)
|
||||
args: [blocked, --flags, --json]
|
||||
stdin: "e2e-mol\ne2e-mol.1\ne2e-mol.2\ne2e-no-such-row\n"
|
||||
compare: json
|
||||
pending: {slice: "SRV-1", reason: "bd blocked --flags reads listBlockingAnnotations is_blocked behind dependencies.blocking.isBlocked, which the reference server does not advertise, so the client refuses at its capability preflight (pinned passing against the current server by backend/http TestE2E_BlockedFlagsOverHTTP); remove the mark when reference_server.json is upgraded"}
|
||||
- id: gc-blocked-flags-raw
|
||||
source: gc bdstore_ready_projection.go readiness door (the stored is_blocked column, bd blocked --flags --raw --json, ids on stdin)
|
||||
args: [blocked, --flags, --raw, --json]
|
||||
stdin: "e2e-mol\ne2e-mol.1\ne2e-mol.2\ne2e-no-such-row\n"
|
||||
compare: json
|
||||
pending: {slice: "SRV-1", reason: "bd blocked --flags reads listBlockingAnnotations is_blocked behind dependencies.blocking.isBlocked, which the reference server does not advertise, so the client refuses at its capability preflight (pinned passing against the current server by backend/http TestE2E_BlockedFlagsOverHTTP); remove the mark when reference_server.json is upgraded"}
|
||||
- id: gc-blocked-parent
|
||||
source: bd blocked --parent (the molecule-scoped blocked listing)
|
||||
args: [blocked, --json, --parent, e2e-mol]
|
||||
pending: {slice: "SRV-1", reason: "bd blocked dials listBlockedIssues behind blocked.list, which the reference server does not advertise, so the client refuses at its capability preflight (pinned passing against the current server by backend/http TestE2E_BlockedOverHTTP); remove the mark when reference_server.json is upgraded"}
|
||||
|
||||
# ---------------------------------------------------------------- molecules
|
||||
- id: mc-mol-current
|
||||
|
|
|
|||
287
backend/http/e2e_blocked_flags_test.go
Normal file
287
backend/http/e2e_blocked_flags_test.go
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
//go:build cgo
|
||||
|
||||
package bdhttp_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os/exec"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/issueops"
|
||||
)
|
||||
|
||||
// runBDStdin is runBD with stdin.
|
||||
func runBDStdin(t *testing.T, f *remoteRolesFixture, stdin string, args ...string) bdResult {
|
||||
t.Helper()
|
||||
cmd := exec.Command(f.bin, args...)
|
||||
cmd.Dir = f.dir
|
||||
cmd.Env = minimalBDEnv(f.dir)
|
||||
cmd.Stdin = strings.NewReader(stdin)
|
||||
var o, e strings.Builder
|
||||
cmd.Stdout, cmd.Stderr = &o, &e
|
||||
err := cmd.Run()
|
||||
code := 0
|
||||
var exitErr *exec.ExitError
|
||||
if errors.As(err, &exitErr) {
|
||||
code = exitErr.ExitCode()
|
||||
} else if err != nil {
|
||||
t.Fatalf("run bd %v: %v", args, err)
|
||||
}
|
||||
return bdResult{stdout: o.String(), stderr: e.String(), code: code}
|
||||
}
|
||||
|
||||
type blockedFlagRow struct {
|
||||
ID string `json:"id"`
|
||||
IsBlocked bool `json:"is_blocked"`
|
||||
}
|
||||
|
||||
func parseBlockedFlags(t *testing.T, out string) []blockedFlagRow {
|
||||
t.Helper()
|
||||
var rows []blockedFlagRow
|
||||
if err := json.Unmarshal([]byte(strings.TrimSpace(out)), &rows); err != nil {
|
||||
t.Fatalf("parse bd blocked --flags --json: %v\n%s", err, out)
|
||||
}
|
||||
if rows == nil {
|
||||
t.Fatalf("bd blocked --flags --json printed null, want an array: %s", out)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// flagStdin is every id the fixture created, in title order, plus an id that
|
||||
// names no row, a blank line and a repeat: the omitted, ignored and collapsed
|
||||
// cases.
|
||||
func flagStdin(f *remoteRolesFixture) string {
|
||||
titles := make([]string, 0, len(f.ids))
|
||||
for title := range f.ids {
|
||||
titles = append(titles, title)
|
||||
}
|
||||
sort.Strings(titles)
|
||||
var b strings.Builder
|
||||
for _, title := range titles {
|
||||
b.WriteString(f.ids[title] + "\n")
|
||||
}
|
||||
b.WriteString("\n " + f.ids[titles[0]] + " \ne2e-no-such-row\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// TestE2E_BlockedFlagsOverHTTP runs `bd blocked --flags --json` (the blocked
|
||||
// flag per id read from stdin, the readiness column gc projects) through the
|
||||
// real `bd` binary against an in-process `bd serve` and against a local
|
||||
// embedded workspace holding the same graph, and requires the same JSON once
|
||||
// each generated id is mapped to its title. Over HTTP the read is
|
||||
// listBlockingAnnotations with is_blocked; an older server's handshake is
|
||||
// refused before the dial, naming dependencies.blocking.isBlocked.
|
||||
//
|
||||
// It also pins that this is the FLAG and not the listing: a row whose stored
|
||||
// flag is set with no nameable blocker reads true here and is absent from
|
||||
// `bd blocked --json`.
|
||||
func TestE2E_BlockedFlagsOverHTTP(t *testing.T) {
|
||||
skipUnlessEmbeddedDolt(t)
|
||||
bin := buildBD(t)
|
||||
|
||||
seed := func(f *remoteRolesFixture) {
|
||||
f.seed()
|
||||
blocker := f.create("blocker", "-t", "task")
|
||||
gp := f.create("gate-parent", "-t", "epic")
|
||||
kid := f.create("gate-kid", "-t", "task")
|
||||
f.mustRun(nil, "dep", "add", kid, gp, "--type", "parent-child")
|
||||
f.mustRun(nil, "dep", "add", gp, blocker)
|
||||
}
|
||||
|
||||
t.Run("served equals local", func(t *testing.T) {
|
||||
addr := startE2EServer(t)
|
||||
local := newEmbeddedFixture(t, bin)
|
||||
seed(local)
|
||||
served := newHTTPFixture(t, bin, addr)
|
||||
seed(served)
|
||||
|
||||
lr := runBDStdin(t, local, flagStdin(local), "blocked", "--flags", "--json")
|
||||
sr := runBDStdin(t, served, flagStdin(served), "blocked", "--flags", "--json")
|
||||
if lr.code != 0 || sr.code != 0 {
|
||||
t.Fatalf("exit local=%d served=%d\nlocal: %s %s\nserved: %s %s", lr.code, sr.code, lr.stdout, lr.stderr, sr.stdout, sr.stderr)
|
||||
}
|
||||
normalize := func(f *remoteRolesFixture, rows []blockedFlagRow) []blockedFlagRow {
|
||||
titleOf := map[string]string{}
|
||||
for title, id := range f.ids {
|
||||
titleOf[id] = title
|
||||
}
|
||||
out := make([]blockedFlagRow, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
if title, ok := titleOf[row.ID]; ok {
|
||||
row.ID = title
|
||||
}
|
||||
out = append(out, row)
|
||||
}
|
||||
return out
|
||||
}
|
||||
want := normalize(local, parseBlockedFlags(t, lr.stdout))
|
||||
got := normalize(served, parseBlockedFlags(t, sr.stdout))
|
||||
if !reflect.DeepEqual(want, got) {
|
||||
t.Errorf("served bd blocked --flags --json differs from the local command:\nlocal: %v\nserved: %v", want, got)
|
||||
}
|
||||
if len(want) != len(local.ids) {
|
||||
t.Errorf("local answered %d rows for %d ids (the unknown id omitted, the repeat collapsed): %v", len(want), len(local.ids), want)
|
||||
}
|
||||
blocked := map[string]bool{}
|
||||
for _, row := range got {
|
||||
blocked[row.ID] = row.IsBlocked
|
||||
}
|
||||
for title, wantBlocked := range map[string]bool{
|
||||
"loner": true, "child-x": true, "gate-parent": true, "gate-kid": true,
|
||||
"blocker": false, "child-b": false, "parent": false,
|
||||
} {
|
||||
if blocked[title] != wantBlocked {
|
||||
t.Errorf("%s is_blocked = %v, want %v (rows %v)", title, blocked[title], wantBlocked, got)
|
||||
}
|
||||
}
|
||||
// Byte-for-byte the same members in the same order.
|
||||
if strings.Count(lr.stdout, "\n") != strings.Count(sr.stdout, "\n") {
|
||||
t.Errorf("line counts differ:\nlocal:\n%s\nserved:\n%s", lr.stdout, sr.stdout)
|
||||
}
|
||||
// Nothing piped is an empty array.
|
||||
if r := runBDStdin(t, served, "", "blocked", "--flags", "--json"); r.code != 0 || strings.TrimSpace(r.stdout) != "[]" {
|
||||
t.Errorf("empty stdin: exit %d stdout %q, want [] and exit 0", r.code, r.stdout)
|
||||
}
|
||||
// The listing's filters are refused, not silently ignored.
|
||||
if r := runBDStdin(t, served, "x\n", "blocked", "--flags", "--json", "--label", "a"); r.code != 1 {
|
||||
t.Errorf("--flags --label exited %d, want 1: %s", r.code, r.stdout)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the flag, not the listing", func(t *testing.T) {
|
||||
addr, reference := startE2EServerWithStore(t, e2eProjectID, e2eDatabase)
|
||||
served := newHTTPFixture(t, bin, addr)
|
||||
stale := served.create("stale")
|
||||
if err := reference.RunEventsMaintenanceTx(context.Background(), func(ctx context.Context, tx issueops.DBTX) error {
|
||||
_, err := tx.ExecContext(ctx, "UPDATE issues SET is_blocked = 1 WHERE id = ?", stale)
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatalf("set the stale flag: %v", err)
|
||||
}
|
||||
rows := parseBlockedFlags(t, runBDStdin(t, served, stale+"\n", "blocked", "--flags", "--json").stdout)
|
||||
if len(rows) != 1 || rows[0].ID != stale || !rows[0].IsBlocked {
|
||||
t.Errorf("--flags for a stale-flagged row = %v, want [{%s true}]", rows, stale)
|
||||
}
|
||||
listing := served.mustRun(nil, "blocked", "--json").stdout
|
||||
if strings.Contains(listing, stale) {
|
||||
t.Errorf("bd blocked --json lists %s, which has no nameable blocker: %s", stale, listing)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("raw is the stored column", func(t *testing.T) {
|
||||
addr, reference := startE2EServerWithStore(t, e2eProjectID, e2eDatabase)
|
||||
local := newEmbeddedFixture(t, bin)
|
||||
seed(local)
|
||||
served := newHTTPFixture(t, bin, addr)
|
||||
seed(served)
|
||||
|
||||
flagsOf := func(f *remoteRolesFixture, stdin string, args ...string) map[string]bool {
|
||||
t.Helper()
|
||||
r := runBDStdin(t, f, stdin, append([]string{"blocked", "--flags", "--json"}, args...)...)
|
||||
if r.code != 0 {
|
||||
t.Fatalf("bd blocked --flags --json %v exited %d: %s %s", args, r.code, r.stdout, r.stderr)
|
||||
}
|
||||
titleOf := map[string]string{}
|
||||
for title, id := range f.ids {
|
||||
titleOf[id] = title
|
||||
}
|
||||
out := map[string]bool{}
|
||||
for _, row := range parseBlockedFlags(t, r.stdout) {
|
||||
key := row.ID
|
||||
if title, ok := titleOf[row.ID]; ok {
|
||||
key = title
|
||||
}
|
||||
out[key] = row.IsBlocked
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
localRaw := flagsOf(local, flagStdin(local), "--raw")
|
||||
servedRaw := flagsOf(served, flagStdin(served), "--raw")
|
||||
if !reflect.DeepEqual(localRaw, servedRaw) {
|
||||
t.Errorf("served --raw differs from local --raw:\nlocal: %v\nserved: %v", localRaw, servedRaw)
|
||||
}
|
||||
lr := runBDStdin(t, local, flagStdin(local), "blocked", "--flags", "--json", "--raw")
|
||||
sr := runBDStdin(t, served, flagStdin(served), "blocked", "--flags", "--json", "--raw")
|
||||
if strings.Count(lr.stdout, "\n") != strings.Count(sr.stdout, "\n") {
|
||||
t.Errorf("--raw line counts differ:\nlocal:\n%s\nserved:\n%s", lr.stdout, sr.stdout)
|
||||
}
|
||||
|
||||
// child-x is blocked ONLY by an unsatisfied external ref: the policy
|
||||
// flag says blocked, the stored column does not.
|
||||
decorated := flagsOf(served, flagStdin(served))
|
||||
if !decorated["child-x"] || servedRaw["child-x"] || localRaw["child-x"] {
|
||||
t.Errorf("child-x (externally blocked only): --flags %v, --raw served %v local %v; want true, false, false",
|
||||
decorated["child-x"], servedRaw["child-x"], localRaw["child-x"])
|
||||
}
|
||||
// Locally blocked rows read the same either way.
|
||||
for _, title := range []string{"loner", "gate-parent", "gate-kid", "blocker"} {
|
||||
if decorated[title] != servedRaw[title] {
|
||||
t.Errorf("%s: --flags %v, --raw %v; a local blocker is the column", title, decorated[title], servedRaw[title])
|
||||
}
|
||||
}
|
||||
|
||||
// A stale flag (set, no blocker) is the column, so both read true.
|
||||
stale := served.create("stale")
|
||||
if err := reference.RunEventsMaintenanceTx(context.Background(), func(ctx context.Context, tx issueops.DBTX) error {
|
||||
_, err := tx.ExecContext(ctx, "UPDATE issues SET is_blocked = 1 WHERE id = ?", stale)
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatalf("set the stale flag: %v", err)
|
||||
}
|
||||
if got := flagsOf(served, stale+"\n", "--raw"); !got["stale"] {
|
||||
t.Errorf("--raw for the stale-flagged row = %v, want true", got)
|
||||
}
|
||||
if got := flagsOf(served, stale+"\n"); !got["stale"] {
|
||||
t.Errorf("--flags for the stale-flagged row = %v, want true", got)
|
||||
}
|
||||
|
||||
// --raw qualifies --flags only.
|
||||
if r := runBDStdin(t, served, "", "blocked", "--json", "--raw"); r.code != 1 || !strings.Contains(r.stdout+r.stderr, "--raw") {
|
||||
t.Errorf("bd blocked --raw without --flags: exit %d %s %s, want exit 1 naming --raw", r.code, r.stdout, r.stderr)
|
||||
}
|
||||
|
||||
// A server that applies the policy answers the decorated flag and the
|
||||
// wire cannot ask it for the column: --raw is refused there, before
|
||||
// the annotation read, rather than answered with the policy flag.
|
||||
proxyAddr, counter := startMaskingProxy(t, addr, func(body map[string]any) {
|
||||
caps, _ := body["capabilities"].([]any)
|
||||
body["capabilities"] = append(caps, "policy.external_dependencies")
|
||||
})
|
||||
enforced := newHTTPFixture(t, bin, proxyAddr)
|
||||
counter.reset()
|
||||
r := runBDStdin(t, enforced, served.ids["child-x"]+"\n", "blocked", "--flags", "--json", "--raw")
|
||||
if r.code != 1 || !strings.Contains(r.stdout+r.stderr, "policy.external_dependencies") {
|
||||
t.Errorf("--raw against a policy server: exit %d %s %s, want exit 1 naming the policy token", r.code, r.stdout, r.stderr)
|
||||
}
|
||||
for _, p := range counter.snapshot() {
|
||||
if strings.Contains(p, "/v0/beads/dependencies/blocking") {
|
||||
t.Errorf("a refused --raw dialed %s", p)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("older server mask", func(t *testing.T) {
|
||||
addr := startE2EServer(t)
|
||||
proxyAddr, counter := startMaskingProxy(t, addr, mcContextMask)
|
||||
f := newHTTPFixture(t, bin, proxyAddr)
|
||||
counter.reset()
|
||||
r := runBDStdin(t, f, "e2e-anything\n", "blocked", "--flags", "--json")
|
||||
if r.code != 1 {
|
||||
t.Fatalf("bd blocked --flags against a server without the token exited %d, want 1: %s", r.code, r.stdout)
|
||||
}
|
||||
if !strings.Contains(r.stdout+r.stderr, "dependencies.blocking.isBlocked") {
|
||||
t.Errorf("refusal does not name the missing capability: stdout=%s stderr=%s", r.stdout, r.stderr)
|
||||
}
|
||||
for _, p := range counter.snapshot() {
|
||||
if strings.Contains(p, "/v0/beads/dependencies/blocking") {
|
||||
t.Errorf("a refused bd blocked --flags dialed %s", p)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
229
backend/http/e2e_blocked_test.go
Normal file
229
backend/http/e2e_blocked_test.go
Normal file
|
|
@ -0,0 +1,229 @@
|
|||
//go:build cgo
|
||||
|
||||
package bdhttp_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestE2E_BlockedOverHTTP runs `bd blocked --json` (the blocked door gc's
|
||||
// readiness projection reads) through the real `bd` binary against an
|
||||
// in-process `bd serve`, and against a local embedded workspace holding the
|
||||
// same graph.
|
||||
//
|
||||
// Over HTTP the CLI takes the store's BlockedLister, which dials
|
||||
// GET /v0/beads/blocked behind blocked.list. The two answers must be the same
|
||||
// JSON once the values that cannot agree between two workspaces (each row's
|
||||
// generated id, and its timestamps) are mapped out: the same rows, the same
|
||||
// members, the same blockers (local, parent-attributed and external), in the
|
||||
// same order. Against a server that does not advertise blocked.list (an older
|
||||
// server's handshake) the client refuses before the dial, naming the token.
|
||||
func TestE2E_BlockedOverHTTP(t *testing.T) {
|
||||
skipUnlessEmbeddedDolt(t)
|
||||
bin := buildBD(t)
|
||||
addr := startE2EServer(t)
|
||||
|
||||
seedBlocked := func(f *remoteRolesFixture) {
|
||||
f.seed()
|
||||
// A plain blocks edge, a blocked parent's child attributed to the
|
||||
// parent, and a labelled blocked row for the filter arms.
|
||||
blocker := f.create("blocker", "-t", "task", "-p", "1")
|
||||
gp := f.create("gate-parent", "-t", "epic", "-p", "2")
|
||||
// Its own priority: rows tied on priority and created_at fall to the
|
||||
// id order, and ids are generated per workspace, so a tie would order
|
||||
// the two workspaces differently.
|
||||
kid := f.create("gate-kid", "-t", "task", "-p", "3")
|
||||
tagged := f.create("tagged", "-t", "task", "-p", "1", "-l", "lane:a")
|
||||
// Blocked by nothing but an unsatisfied external ref, as child-x is,
|
||||
// and labelled: the decorator lists such rows itself, after the label
|
||||
// query ran, so the filter arms must judge them too.
|
||||
extTagged := f.create("ext-tagged", "-t", "task", "-p", "4", "-l", "lane:a")
|
||||
f.mustRun(nil, "dep", "add", kid, gp, "--type", "parent-child")
|
||||
f.mustRun(nil, "dep", "add", gp, blocker)
|
||||
f.mustRun(nil, "dep", "add", tagged, blocker)
|
||||
f.mustRun(nil, "dep", "add", extTagged, "external:other:cap")
|
||||
}
|
||||
|
||||
local := newEmbeddedFixture(t, bin)
|
||||
seedBlocked(local)
|
||||
served := newHTTPFixture(t, bin, addr)
|
||||
seedBlocked(served)
|
||||
|
||||
for _, args := range [][]string{
|
||||
{"blocked", "--json"},
|
||||
{"blocked", "--json", "--label", "lane:a"},
|
||||
{"blocked", "--json", "--label-any", "lane:a"},
|
||||
{"blocked", "--json", "--exclude-label", "lane:a"},
|
||||
{"blocked", "--json", "--parent", "{gate-parent}"},
|
||||
{"blocked", "--json", "--label", "no-such-label"},
|
||||
} {
|
||||
t.Run(strings.Join(args[1:], " "), func(t *testing.T) {
|
||||
want := local.mustRun(nil, local.expand(args)...).stdout
|
||||
got := served.mustRun(nil, served.expand(args)...).stdout
|
||||
if strings.TrimSpace(want) == "null" || strings.TrimSpace(got) == "null" {
|
||||
t.Fatalf("bd blocked --json printed null: local=%s served=%s", want, got)
|
||||
}
|
||||
if w, g := normalizeBlocked(t, local, want), normalizeBlocked(t, served, got); !reflect.DeepEqual(w, g) {
|
||||
t.Errorf("served bd blocked --json differs from the local command:\nlocal: %v\nserved: %v", w, g)
|
||||
}
|
||||
if w, g := blockedKeyOrder(t, want), blockedKeyOrder(t, got); !reflect.DeepEqual(w, g) {
|
||||
t.Errorf("served member order %v differs from the local command's %v", g, w)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("names the external blocker", func(t *testing.T) {
|
||||
got := normalizeBlocked(t, served, served.mustRun(nil, "blocked", "--json").stdout)
|
||||
found := false
|
||||
for _, row := range got {
|
||||
if row["id"] == "child-x" {
|
||||
found = reflect.DeepEqual(row["blocked_by"], []any{"external:other:cap"})
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("served bd blocked --json does not list child-x blocked by its external ref: %v", got)
|
||||
}
|
||||
})
|
||||
|
||||
// The arms above compare the two answers, which agree just as well when
|
||||
// both list a row the filter rules out. These pin which rows each filter
|
||||
// leaves, the external-only ones (child-x unlabelled, ext-tagged
|
||||
// labelled) among them.
|
||||
for _, tc := range []struct {
|
||||
args []string
|
||||
want []string // the whole listing, when set
|
||||
listed, ruled []string
|
||||
}{
|
||||
{args: []string{"--label", "lane:a"}, want: []string{"ext-tagged", "tagged"}},
|
||||
{args: []string{"--label-any", "lane:a"}, want: []string{"ext-tagged", "tagged"}},
|
||||
{args: []string{"--label", "no-such-label"}, want: []string{}},
|
||||
{args: []string{"--exclude-label", "lane:a"}, listed: []string{"child-x"}, ruled: []string{"ext-tagged", "tagged"}},
|
||||
} {
|
||||
t.Run("filters external-only rows "+strings.Join(tc.args, " "), func(t *testing.T) {
|
||||
for _, f := range []struct {
|
||||
name string
|
||||
f *remoteRolesFixture
|
||||
}{{"local", local}, {"served", served}} {
|
||||
got := f.f.titlesOf(f.f.mustRun(nil, append([]string{"blocked", "--json"}, tc.args...)...).stdout)
|
||||
if tc.want != nil && !slices.Equal(got, tc.want) {
|
||||
t.Errorf("%s bd blocked %s listed %v, want %v", f.name, strings.Join(tc.args, " "), got, tc.want)
|
||||
}
|
||||
for _, title := range tc.listed {
|
||||
if !slices.Contains(got, title) {
|
||||
t.Errorf("%s bd blocked %s does not list %s: %v", f.name, strings.Join(tc.args, " "), title, got)
|
||||
}
|
||||
}
|
||||
for _, title := range tc.ruled {
|
||||
if slices.Contains(got, title) {
|
||||
t.Errorf("%s bd blocked %s lists %s, which the filter rules out: %v", f.name, strings.Join(tc.args, " "), title, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("older server mask", func(t *testing.T) {
|
||||
proxyAddr, counter := startMaskingProxy(t, addr, mcContextMask)
|
||||
f := newHTTPFixture(t, bin, proxyAddr)
|
||||
counter.reset()
|
||||
r := f.run(nil, "blocked", "--json")
|
||||
if r.code != 1 {
|
||||
t.Fatalf("bd blocked against a server without blocked.list exited %d, want 1: %s", r.code, r.stdout)
|
||||
}
|
||||
if !strings.Contains(r.stdout+r.stderr, "blocked.list") {
|
||||
t.Errorf("refusal does not name the missing capability: stdout=%s stderr=%s", r.stdout, r.stderr)
|
||||
}
|
||||
for _, p := range counter.snapshot() {
|
||||
if strings.Contains(p, "/v0/beads/blocked") {
|
||||
t.Errorf("a refused bd blocked dialed %s; the refusal must come before the dial", p)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// normalizeBlocked parses `bd blocked --json` and maps out what two
|
||||
// workspaces cannot share: each id (and each blocker id) becomes the title the
|
||||
// fixture created it under, and every timestamp member is blanked.
|
||||
func normalizeBlocked(t *testing.T, f *remoteRolesFixture, out string) []map[string]any {
|
||||
t.Helper()
|
||||
var rows []map[string]any
|
||||
if err := json.Unmarshal([]byte(strings.TrimSpace(out)), &rows); err != nil {
|
||||
t.Fatalf("parse bd blocked --json: %v\n%s", err, out)
|
||||
}
|
||||
titleOf := map[string]string{}
|
||||
for title, id := range f.ids {
|
||||
titleOf[id] = title
|
||||
}
|
||||
var walk func(key string, v any) any
|
||||
walk = func(key string, v any) any {
|
||||
switch v := v.(type) {
|
||||
case map[string]any:
|
||||
for k, inner := range v {
|
||||
v[k] = walk(k, inner)
|
||||
}
|
||||
return v
|
||||
case []any:
|
||||
for i := range v {
|
||||
v[i] = walk("", v[i])
|
||||
}
|
||||
return v
|
||||
case string:
|
||||
if strings.HasSuffix(key, "_at") {
|
||||
return "<time>"
|
||||
}
|
||||
if title, ok := titleOf[v]; ok {
|
||||
return title
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
for _, row := range rows {
|
||||
walk("", row)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// blockedKeyOrder is the member order of each row as printed, so the two
|
||||
// encodings are compared as text, not only as values.
|
||||
func blockedKeyOrder(t *testing.T, out string) [][]string {
|
||||
t.Helper()
|
||||
var rows []json.RawMessage
|
||||
if err := json.Unmarshal([]byte(strings.TrimSpace(out)), &rows); err != nil {
|
||||
t.Fatalf("parse bd blocked --json: %v\n%s", err, out)
|
||||
}
|
||||
order := make([][]string, 0, len(rows))
|
||||
for _, raw := range rows {
|
||||
dec := json.NewDecoder(strings.NewReader(string(raw)))
|
||||
var keys []string
|
||||
depth := 0
|
||||
for {
|
||||
tok, err := dec.Token()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
switch v := tok.(type) {
|
||||
case json.Delim:
|
||||
if v == '{' || v == '[' {
|
||||
depth++
|
||||
} else {
|
||||
depth--
|
||||
}
|
||||
case string:
|
||||
if depth == 1 {
|
||||
keys = append(keys, v)
|
||||
// Skip the value.
|
||||
var skip json.RawMessage
|
||||
if err := dec.Decode(&skip); err != nil {
|
||||
t.Fatalf("decode value of %s: %v", v, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
order = append(order, keys)
|
||||
}
|
||||
return order
|
||||
}
|
||||
|
|
@ -814,6 +814,8 @@ func e2eServeConfig(t *testing.T, s storage.DoltStorage, projectID, database str
|
|||
fail("LeaseReclaimer")
|
||||
cfg.Heartbeater, err = s.Heartbeater()
|
||||
fail("Heartbeater")
|
||||
cfg.BlockedLister, err = s.BlockedLister()
|
||||
fail("BlockedLister")
|
||||
cfg.Relations, err = s.IssueRelations()
|
||||
fail("IssueRelations")
|
||||
cfg.Commenter, err = s.Commenter()
|
||||
|
|
|
|||
|
|
@ -49,6 +49,7 @@ go_library(
|
|||
"backup_restore.go",
|
||||
"batch.go",
|
||||
"batch_proxied_server.go",
|
||||
"blocked_flags.go",
|
||||
"bootstrap.go",
|
||||
"branch.go",
|
||||
"capability_registry.go",
|
||||
|
|
@ -568,6 +569,7 @@ go_test(
|
|||
"batch_parity_test.go",
|
||||
"batch_test.go",
|
||||
"blocked_embedded_test.go",
|
||||
"blocked_flags_test.go",
|
||||
"blocked_proxied_integration_test.go",
|
||||
"bootstrap_backend_guard_test.go",
|
||||
"bootstrap_embedded_test.go",
|
||||
|
|
|
|||
|
|
@ -234,7 +234,7 @@ func TestEmbeddedBlockedLabelFilters(t *testing.T) {
|
|||
}
|
||||
})
|
||||
|
||||
// blockedFilterFromFlags normalizes, as every sibling label filter does.
|
||||
// the blocked role normalizes, as every sibling label filter does.
|
||||
// Without it an untrimmed value returns nothing and is indistinguishable
|
||||
// from "nothing blocked carries that label".
|
||||
t.Run("leading_space_is_trimmed_like_every_other_label_filter", func(t *testing.T) {
|
||||
|
|
|
|||
167
cmd/bd/blocked_flags.go
Normal file
167
cmd/bd/blocked_flags.go
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/storage/uow"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// blockedFlagRow is one line of `bd blocked --flags --json`: an id the caller
|
||||
// named and the blocked flag bd holds for it.
|
||||
type blockedFlagRow struct {
|
||||
ID string `json:"id"`
|
||||
IsBlocked bool `json:"is_blocked"`
|
||||
}
|
||||
|
||||
// blockedFlagFilterFlags are the listing's filters, which --flags does not
|
||||
// take: it answers about the ids it is handed, not about a set it derives.
|
||||
var blockedFlagFilterFlags = []string{"parent", "label", "label-any", "exclude-label"}
|
||||
|
||||
// runBlockedFlags is `bd blocked --flags`: the blocked flag for each id read
|
||||
// from stdin (one per line; blank lines and repeats ignored), through the
|
||||
// issueops.BlockedFlags library entry over the route's BlockingAnnotator.
|
||||
//
|
||||
// IT IS THE FLAG, NOT THE LISTING. The listing narrows the stored flag to
|
||||
// rows bd can name a blocker for; this answers the flag itself, the column
|
||||
// `bd ready` filters on, so a row whose flag is set with no nameable blocker
|
||||
// reads true here and is absent from the listing. Where the
|
||||
// external-dependency policy applies, an unsatisfied external: blocker sets
|
||||
// the flag as it keeps the row out of `bd ready`.
|
||||
//
|
||||
// Every id that names a row on either plane is answered, in the order the ids
|
||||
// were first given, a closed row included (its flag is whatever is stored);
|
||||
// an id naming no row is omitted. Over HTTP the read is
|
||||
// listBlockingAnnotations with is_blocked, behind
|
||||
// dependencies.blocking.isBlocked; a server without that token is refused
|
||||
// before the dial, naming it.
|
||||
//
|
||||
// --raw answers the stored column itself, without the external-dependency
|
||||
// decoration (blockedFlagsAnnotator): exactly what reading is_blocked from
|
||||
// the issues and wisps tables returns.
|
||||
func runBlockedFlags(cmd *cobra.Command, ctx context.Context, in io.Reader) error {
|
||||
for _, name := range blockedFlagFilterFlags {
|
||||
if cmd.Flags().Changed(name) {
|
||||
return HandleErrorRespectJSON("--flags answers the ids read from stdin and takes no --%s", name)
|
||||
}
|
||||
}
|
||||
ids, err := readBlockedFlagIDs(in)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("reading ids from stdin: %v", err)
|
||||
}
|
||||
raw, _ := cmd.Flags().GetBool("raw")
|
||||
annotator, err := blockedFlagsAnnotator(ctx, raw)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
flags, err := issueops.BlockedFlags(ctx, annotator, ids)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
rows := make([]blockedFlagRow, 0, len(flags))
|
||||
seen := make(map[string]bool, len(ids))
|
||||
for _, id := range ids {
|
||||
blocked, ok := flags[id]
|
||||
if !ok || seen[id] {
|
||||
continue
|
||||
}
|
||||
seen[id] = true
|
||||
rows = append(rows, blockedFlagRow{ID: id, IsBlocked: blocked})
|
||||
}
|
||||
if jsonOutput {
|
||||
return outputJSON(rows)
|
||||
}
|
||||
for _, row := range rows {
|
||||
state := "not blocked"
|
||||
if row.IsBlocked {
|
||||
state = "blocked"
|
||||
}
|
||||
fmt.Printf("%s\t%s\n", row.ID, state)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// readBlockedFlagIDs reads one id per line, trimmed, skipping blank lines.
|
||||
func readBlockedFlagIDs(in io.Reader) ([]string, error) {
|
||||
var ids []string
|
||||
scanner := bufio.NewScanner(in)
|
||||
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
|
||||
for scanner.Scan() {
|
||||
if id := strings.TrimSpace(scanner.Text()); id != "" {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
return ids, scanner.Err()
|
||||
}
|
||||
|
||||
// blockedFlagsAnnotator is the BlockingAnnotator for the route this
|
||||
// invocation runs: the store's own accessor on the direct routes (dolt,
|
||||
// embedded dolt, HTTP), and the proxied-server provider's on the proxied one.
|
||||
// Both carry the external-dependency decoration the rest of bd reads through.
|
||||
//
|
||||
// With raw it is the same role taken from BENEATH every decorator (the
|
||||
// innermost store, the innermost provider), so the answer is the stored
|
||||
// is_blocked column and nothing else: an unsatisfied external: blocker does
|
||||
// not set it, because the column has never known about other projects.
|
||||
func blockedFlagsAnnotator(ctx context.Context, raw bool) (issueops.BlockingAnnotator, error) {
|
||||
if !raw {
|
||||
if usesProxiedServer() {
|
||||
return proxiedBlockingAnnotator()
|
||||
}
|
||||
if store == nil {
|
||||
return nil, fmt.Errorf("no storage available")
|
||||
}
|
||||
return store.BlockingAnnotator()
|
||||
}
|
||||
if usesProxiedServer() {
|
||||
if uowProvider == nil {
|
||||
return nil, fmt.Errorf("proxied-server UOW provider not initialized")
|
||||
}
|
||||
src, ok := uow.UnwrapProvider(uowProvider).(uow.BlockingAnnotatorSource)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("proxied-server provider %T does not offer the blocking-decoration surface", uowProvider)
|
||||
}
|
||||
return src.BlockingAnnotator()
|
||||
}
|
||||
if store == nil {
|
||||
return nil, fmt.Errorf("no storage available")
|
||||
}
|
||||
base := storage.UnwrapStore(store)
|
||||
if err := refuseRawFlagsFromAPolicyServer(ctx, base); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return base.BlockingAnnotator()
|
||||
}
|
||||
|
||||
// refuseRawFlagsFromAPolicyServer refuses --raw against a served workspace
|
||||
// whose server applies the external-dependency policy itself
|
||||
// (policy.external_dependencies). That server's blocking annotation already
|
||||
// sets the flag for an unsatisfied external: blocker, the v0 wire has no
|
||||
// member that asks it for the bare column, and the decorated flag cannot be
|
||||
// turned back into the column on this side (a row that is externally blocked
|
||||
// may or may not also carry the stored flag). Answering anyway would be the
|
||||
// decorated flag spelled as the raw one. Against a server that does not apply
|
||||
// the policy, its annotation IS the column, and --raw is served.
|
||||
func refuseRawFlagsFromAPolicyServer(ctx context.Context, base storage.DoltStorage) error {
|
||||
prober, ok := base.(storage.ExternalDependencyPolicyProber)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
enforced, err := prober.ServerEnforcesExternalDependencyPolicy(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if enforced {
|
||||
return fmt.Errorf("bd blocked --flags --raw is not served by this workspace's server: it applies the " +
|
||||
"external-dependency policy (policy.external_dependencies) to the blocked flag it answers, and the v0 " +
|
||||
"wire cannot ask it for the stored column; use bd blocked --flags (the policy-aware flag)")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
57
cmd/bd/blocked_flags_test.go
Normal file
57
cmd/bd/blocked_flags_test.go
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// TestBlockedFlagsRefusesEveryListingFilter pins blockedFlagFilterFlags to the
|
||||
// flags blockedCmd registers. --flags answers the ids read from stdin, so a
|
||||
// listing filter it does not refuse is silently ignored: a filter added to
|
||||
// blockedCmd but not to the refusal list would answer every id while the
|
||||
// caller believes the answer was narrowed. The reverse direction catches an
|
||||
// entry naming no registered flag, which Changed never reports as set.
|
||||
//
|
||||
// It walks Flags() and PersistentFlags() with VisitAll, not LocalFlags(),
|
||||
// which would merge the root's persistent flags into blockedCmd for the rest
|
||||
// of the process (see TestNoSubcommandShadowsRootJSONFlag). A root flag that
|
||||
// an earlier in-process run already merged in is skipped by identity, and
|
||||
// cobra's own --help by its annotation.
|
||||
func TestBlockedFlagsRefusesEveryListingFilter(t *testing.T) {
|
||||
// The flags --flags itself reads: the mode switch and its qualifier.
|
||||
modeFlags := []string{"flags", "raw"}
|
||||
|
||||
var registered []string
|
||||
visit := func(f *pflag.Flag) {
|
||||
if f == rootCmd.PersistentFlags().Lookup(f.Name) || len(f.Annotations[cobra.FlagSetByCobraAnnotation]) > 0 {
|
||||
return
|
||||
}
|
||||
if !slices.Contains(registered, f.Name) {
|
||||
registered = append(registered, f.Name)
|
||||
}
|
||||
}
|
||||
blockedCmd.PersistentFlags().VisitAll(visit)
|
||||
blockedCmd.Flags().VisitAll(visit)
|
||||
|
||||
for _, name := range modeFlags {
|
||||
if !slices.Contains(registered, name) {
|
||||
t.Errorf("blockedCmd registers no --%s; this test's mode flags are stale", name)
|
||||
}
|
||||
}
|
||||
for _, name := range registered {
|
||||
if !slices.Contains(modeFlags, name) && !slices.Contains(blockedFlagFilterFlags, name) {
|
||||
t.Errorf("--%s is registered on blockedCmd but --flags does not refuse it: add it to blockedFlagFilterFlags, or to this test's mode flags if --flags reads it", name)
|
||||
}
|
||||
}
|
||||
for _, name := range blockedFlagFilterFlags {
|
||||
if slices.Contains(modeFlags, name) {
|
||||
t.Errorf("blockedFlagFilterFlags refuses --%s, which --flags itself reads", name)
|
||||
}
|
||||
if !slices.Contains(registered, name) {
|
||||
t.Errorf("blockedFlagFilterFlags names --%s, which blockedCmd does not register", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,8 @@ package main
|
|||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"os/exec"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
|
|
@ -81,6 +83,68 @@ func TestProxiedServerBlocked(t *testing.T) {
|
|||
}
|
||||
})
|
||||
|
||||
t.Run("flags_reads_ids_from_stdin", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
p := newSharedProxiedProject(t, bd, "bkf")
|
||||
blocker := bdProxiedCreate(t, bd, p.dir, "Flag blocker")
|
||||
dependent := bdProxiedCreate(t, bd, p.dir, "Flag dependent", "--deps", "depends-on:"+blocker.ID)
|
||||
|
||||
cmd := exec.Command(bd, "blocked", "--flags", "--json")
|
||||
cmd.Dir = p.dir
|
||||
cmd.Env = bdProxiedEnv(p.dir)
|
||||
cmd.Stdin = strings.NewReader(dependent.ID + "\n" + blocker.ID + "\nbk-no-such-row\n")
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout, cmd.Stderr = &stdout, &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
t.Fatalf("bd blocked --flags --json: %v\nstdout:\n%s\nstderr:\n%s", err, stdout.String(), stderr.String())
|
||||
}
|
||||
var rows []struct {
|
||||
ID string `json:"id"`
|
||||
IsBlocked bool `json:"is_blocked"`
|
||||
}
|
||||
if err := json.Unmarshal(bytes.TrimSpace(stdout.Bytes()), &rows); err != nil {
|
||||
t.Fatalf("parse: %v\n%s", err, stdout.String())
|
||||
}
|
||||
if len(rows) != 2 || rows[0].ID != dependent.ID || !rows[0].IsBlocked || rows[1].ID != blocker.ID || rows[1].IsBlocked {
|
||||
t.Errorf("rows = %+v, want [{%s true} {%s false}] (unknown id omitted)", rows, dependent.ID, blocker.ID)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("flags_raw_is_the_stored_column", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
p := newSharedProxiedProject(t, bd, "bkr")
|
||||
ext := bdProxiedCreate(t, bd, p.dir, "Externally blocked only")
|
||||
if _, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "dep", "add", ext.ID, "external:otherproj:cap"); err != nil {
|
||||
t.Fatalf("dep add external: %v\n%s", err, stderr)
|
||||
}
|
||||
flag := func(args ...string) bool {
|
||||
t.Helper()
|
||||
cmd := exec.Command(bd, append([]string{"blocked", "--flags", "--json"}, args...)...)
|
||||
cmd.Dir = p.dir
|
||||
cmd.Env = bdProxiedEnv(p.dir)
|
||||
cmd.Stdin = strings.NewReader(ext.ID + "\n")
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout, cmd.Stderr = &stdout, &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
t.Fatalf("bd blocked --flags %v: %v\n%s\n%s", args, err, stdout.String(), stderr.String())
|
||||
}
|
||||
var rows []struct {
|
||||
ID string `json:"id"`
|
||||
IsBlocked bool `json:"is_blocked"`
|
||||
}
|
||||
if err := json.Unmarshal(bytes.TrimSpace(stdout.Bytes()), &rows); err != nil || len(rows) != 1 {
|
||||
t.Fatalf("parse %v: %v\n%s", args, err, stdout.String())
|
||||
}
|
||||
return rows[0].IsBlocked
|
||||
}
|
||||
if !flag() {
|
||||
t.Errorf("--flags for an externally blocked row = false, want true (the policy flag)")
|
||||
}
|
||||
if flag("--raw") {
|
||||
t.Errorf("--flags --raw for an externally blocked row = true, want false (the stored column)")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty_case", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
p := newSharedProxiedProject(t, bd, "bk2")
|
||||
|
|
@ -125,4 +189,42 @@ func TestProxiedServerBlocked(t *testing.T) {
|
|||
t.Errorf("non-descendant %s leaked into --parent result", outside.ID)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("label_filters_apply_to_external_only_rows", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
p := newSharedProxiedProject(t, bd, "bkl")
|
||||
// A row blocked only by an unsatisfied external ref is listed by the
|
||||
// unit-of-work decorator after the label query ran, so the filters
|
||||
// must judge it by its own labels, read hydrated.
|
||||
tagged := bdProxiedCreate(t, bd, p.dir, "Externally blocked, labelled", "-l", "lane:a")
|
||||
bare := bdProxiedCreate(t, bd, p.dir, "Externally blocked, unlabelled")
|
||||
for _, id := range []string{tagged.ID, bare.ID} {
|
||||
if _, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "dep", "add", id, "external:otherproj:cap"); err != nil {
|
||||
t.Fatalf("dep add %s external: %v\n%s", id, err, stderr)
|
||||
}
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
args []string
|
||||
want []string
|
||||
}{
|
||||
{nil, []string{tagged.ID, bare.ID}},
|
||||
{[]string{"--label", "lane:a"}, []string{tagged.ID}},
|
||||
{[]string{"--label-any", "lane:a"}, []string{tagged.ID}},
|
||||
{[]string{"--exclude-label", "lane:a"}, []string{bare.ID}},
|
||||
} {
|
||||
got := bdProxiedBlockedJSON(t, bd, p, tc.args...)
|
||||
ids := make([]string, 0, len(got))
|
||||
for _, bi := range got {
|
||||
ids = append(ids, bi.ID)
|
||||
if bi.ID == tagged.ID && !slices.Equal(bi.Labels, []string{"lane:a"}) {
|
||||
t.Errorf("bd blocked %v: %s prints labels %v, want [lane:a]", tc.args, bi.ID, bi.Labels)
|
||||
}
|
||||
}
|
||||
slices.Sort(ids)
|
||||
slices.Sort(tc.want)
|
||||
if !slices.Equal(ids, tc.want) {
|
||||
t.Errorf("bd blocked %v listed %v, want %v", tc.args, ids, tc.want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -332,29 +332,44 @@ func rejectReadyMaxRowsUnderProxiedServer(cmd *cobra.Command) error {
|
|||
return rejectMaxRowsUnderProxiedServer(cmd)
|
||||
}
|
||||
|
||||
// blockedFilterFromFlags builds the blocked-issue filter from blockedCmd's
|
||||
// flags. Both the direct and the proxied-server path call it, so the two
|
||||
// cannot drift as filtering flags are added.
|
||||
func blockedFilterFromFlags(cmd *cobra.Command) types.WorkFilter {
|
||||
var filter types.WorkFilter
|
||||
if parentID, _ := cmd.Flags().GetString("parent"); parentID != "" {
|
||||
filter.ParentID = &parentID
|
||||
}
|
||||
// Normalize as every other label filter does (list_input.go:293-295,
|
||||
// search.go:106, orphans.go:56, workapi/ready.go:56-58). These clauses
|
||||
// match a label EXACTLY, so an untrimmed value silently under-reports:
|
||||
// pflag's CSV split leaves the leading space in the everyday
|
||||
// `--label 'a, b'` form, and `--label 'a,,b'` would AND in a `label = ''`
|
||||
// clause that matches nothing at all. Without this, `--label` would not
|
||||
// mean the same thing here as on the commands next to it -- which is the
|
||||
// promise LabelSetClauses is documented to keep.
|
||||
// blockedRequestFromFlags builds the blocked listing's request from
|
||||
// blockedCmd's flags. Every route calls it, so the routes cannot drift as
|
||||
// filtering flags are added.
|
||||
//
|
||||
// The labels go to the role as written: the role normalizes them, as every
|
||||
// other label filter is normalized (list_input.go, search.go, orphans.go,
|
||||
// workapi/ready.go). These clauses match a label EXACTLY, so an untrimmed
|
||||
// value would silently under-report: pflag's CSV split leaves the leading
|
||||
// space in the everyday `--label 'a, b'` form, and `--label 'a,,b'` would AND
|
||||
// in an empty-label clause that matches nothing at all. Normalizing in the
|
||||
// role rather than here is what makes a served listing normalize the same way
|
||||
// for every client.
|
||||
func blockedRequestFromFlags(cmd *cobra.Command) issueops.BlockedRequest {
|
||||
parentID, _ := cmd.Flags().GetString("parent")
|
||||
labels, _ := cmd.Flags().GetStringSlice("label")
|
||||
labelsAny, _ := cmd.Flags().GetStringSlice("label-any")
|
||||
excludeLabels, _ := cmd.Flags().GetStringSlice("exclude-label")
|
||||
filter.Labels = utils.NormalizeLabels(labels)
|
||||
filter.LabelsAny = utils.NormalizeLabels(labelsAny)
|
||||
filter.ExcludeLabels = utils.NormalizeLabels(excludeLabels)
|
||||
return filter
|
||||
return issueops.BlockedRequest{
|
||||
ParentID: parentID,
|
||||
Labels: labels,
|
||||
LabelsAny: labelsAny,
|
||||
ExcludeLabels: excludeLabels,
|
||||
}
|
||||
}
|
||||
|
||||
// blockedLister is the blocked-listing role for the route this invocation
|
||||
// runs: the store's own BlockedLister accessor on the direct routes (dolt,
|
||||
// embedded dolt, and a registered HTTP backend, where it dials blocked.list
|
||||
// and an older server is refused before the dial naming the token), and the
|
||||
// proxied-server provider's on the proxied one.
|
||||
func blockedLister() (issueops.BlockedLister, error) {
|
||||
if usesProxiedServer() {
|
||||
return proxiedBlockedLister()
|
||||
}
|
||||
if store == nil {
|
||||
return nil, fmt.Errorf("no storage available")
|
||||
}
|
||||
return store.BlockedLister()
|
||||
}
|
||||
|
||||
var blockedCmd = &cobra.Command{
|
||||
|
|
@ -370,17 +385,24 @@ var blockedCmd = &cobra.Command{
|
|||
}
|
||||
}()
|
||||
|
||||
if usesProxiedServer() {
|
||||
return runBlockedProxiedServer(cmd, rootCtx)
|
||||
}
|
||||
// Use global jsonOutput set by PersistentPreRun (respects config.yaml + env vars)
|
||||
// Use factory to respect backend configuration (bd-m2jr: SQLite fallback fix)
|
||||
// One role on every route (blockedLister). Use global jsonOutput set
|
||||
// by PersistentPreRun (respects config.yaml + env vars).
|
||||
ctx := rootCtx
|
||||
blockedFilter := blockedFilterFromFlags(cmd)
|
||||
blocked, err := store.GetBlockedIssues(ctx, blockedFilter)
|
||||
if flagsMode, _ := cmd.Flags().GetBool("flags"); flagsMode {
|
||||
return runBlockedFlags(cmd, ctx, cmd.InOrStdin())
|
||||
}
|
||||
if cmd.Flags().Changed("raw") {
|
||||
return HandleErrorRespectJSON("--raw qualifies --flags (the stored blocked column per id); it has no meaning for the listing")
|
||||
}
|
||||
lister, err := blockedLister()
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
result, err := lister.ListBlocked(ctx, blockedRequestFromFlags(cmd))
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
blocked := result.Items
|
||||
if jsonOutput {
|
||||
if blocked == nil {
|
||||
blocked = []*types.BlockedIssue{}
|
||||
|
|
@ -799,6 +821,8 @@ func init() {
|
|||
blockedCmd.Flags().StringSliceP("label", "l", []string{}, "Filter by labels (AND: must have ALL). Can combine with --label-any")
|
||||
blockedCmd.Flags().StringSlice("label-any", []string{}, "Filter by labels (OR: must have AT LEAST ONE). Can combine with --label")
|
||||
blockedCmd.Flags().StringSlice("exclude-label", []string{}, "Exclude issues that have ANY of these labels")
|
||||
blockedCmd.Flags().Bool("raw", false, "With --flags: the stored blocked column itself, without the external-dependency policy (an unsatisfied external: blocker does not set it)")
|
||||
blockedCmd.Flags().Bool("flags", false, "Print the blocked flag for each id read from stdin (one per line) instead of the listing; with --json, [{\"id\",\"is_blocked\"}]")
|
||||
rootCmd.AddCommand(blockedCmd)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -75,48 +75,19 @@ func runReadyProxiedServer(cmd *cobra.Command, ctx context.Context) error {
|
|||
}
|
||||
}
|
||||
|
||||
func runBlockedProxiedServer(cmd *cobra.Command, ctx context.Context) error {
|
||||
// proxiedBlockedLister hands back the blocked-listing surface for the
|
||||
// proxied-server provider, through the provider's OWN capability accessor:
|
||||
// the accessor is where each layer (the external-dependency decoration among
|
||||
// them) is added.
|
||||
func proxiedBlockedLister() (issueops.BlockedLister, error) {
|
||||
if uowProvider == nil {
|
||||
return HandleError("proxied-server UOW provider not initialized")
|
||||
return nil, errors.New("proxied-server UOW provider not initialized")
|
||||
}
|
||||
uw, err := uowProvider.NewUOW(ctx)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("open unit of work: %v", err)
|
||||
src, ok := uowProvider.(uow.BlockedListerSource)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("proxied-server provider %T does not offer the blocked-listing surface", uowProvider)
|
||||
}
|
||||
defer uw.Close(ctx)
|
||||
|
||||
filter := blockedFilterFromFlags(cmd)
|
||||
|
||||
blocked, err := uw.IssueUseCase().GetBlockedIssues(ctx, filter)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
|
||||
if jsonOutput {
|
||||
if blocked == nil {
|
||||
blocked = []*types.BlockedIssue{}
|
||||
}
|
||||
_ = outputJSON(blocked)
|
||||
return nil
|
||||
}
|
||||
if len(blocked) == 0 {
|
||||
fmt.Printf("\n%s No blocked issues\n\n", ui.RenderPass("✨"))
|
||||
return nil
|
||||
}
|
||||
fmt.Printf("\n%s Blocked issues (%d):\n\n", ui.RenderFail("🚫"), len(blocked))
|
||||
for _, issue := range blocked {
|
||||
fmt.Printf("[%s] %s: %s\n",
|
||||
ui.RenderPriority(issue.Priority),
|
||||
ui.RenderID(issue.ID), issue.Title)
|
||||
blockedBy := issue.BlockedBy
|
||||
if blockedBy == nil {
|
||||
blockedBy = []string{}
|
||||
}
|
||||
fmt.Printf(" Blocked by %d open dependencies: %v\n",
|
||||
issue.BlockedByCount, blockedBy)
|
||||
fmt.Println()
|
||||
}
|
||||
return nil
|
||||
return src.BlockedLister()
|
||||
}
|
||||
|
||||
func runReadyProxiedList(ctx context.Context, uw uow.UnitOfWork, in readyInput) error {
|
||||
|
|
|
|||
|
|
@ -321,6 +321,7 @@ func runServe() error {
|
|||
BatchGetter: roles.batchGetter,
|
||||
LeaseReclaimer: roles.leaseReclaimer,
|
||||
Heartbeater: roles.heartbeater,
|
||||
BlockedLister: roles.blockedLister,
|
||||
Relations: roles.relations,
|
||||
Commenter: roles.commenter,
|
||||
BlockingAnnotator: roles.blocking,
|
||||
|
|
@ -684,6 +685,7 @@ type serveRoleSource interface {
|
|||
BatchGetter() (issueops.BatchGetter, error)
|
||||
LeaseReclaimer() (issueops.LeaseReclaimer, error)
|
||||
Heartbeater() (issueops.Heartbeater, error)
|
||||
BlockedLister() (issueops.BlockedLister, error)
|
||||
IssueRelations() (issueops.Relations, error)
|
||||
Commenter() (issueops.Commenter, error)
|
||||
BlockingAnnotator() (issueops.BlockingAnnotator, error)
|
||||
|
|
@ -753,6 +755,7 @@ func serveIssueRoles(src serveRoleSource, journalEnabled bool) (serveRoles, erro
|
|||
{"batch getter", func() (err error) { roles.batchGetter, err = src.BatchGetter(); return }},
|
||||
{"lease reclaimer", func() (err error) { roles.leaseReclaimer, err = src.LeaseReclaimer(); return }},
|
||||
{"heartbeater", func() (err error) { roles.heartbeater, err = src.Heartbeater(); return }},
|
||||
{"blocked lister", func() (err error) { roles.blockedLister, err = src.BlockedLister(); return }},
|
||||
{"issue relations", func() (err error) { roles.relations, err = src.IssueRelations(); return }},
|
||||
{"commenter", func() (err error) { roles.commenter, err = src.Commenter(); return }},
|
||||
{"blocking annotator", func() (err error) { roles.blocking, err = src.BlockingAnnotator(); return }},
|
||||
|
|
@ -875,6 +878,7 @@ type serveRoles struct {
|
|||
// re-arm (a refresh fires nothing).
|
||||
leaseReclaimer issueops.LeaseReclaimer
|
||||
heartbeater issueops.Heartbeater
|
||||
blockedLister issueops.BlockedLister
|
||||
relations issueops.Relations
|
||||
commenter issueops.Commenter
|
||||
blocking issueops.BlockingAnnotator
|
||||
|
|
|
|||
|
|
@ -521,6 +521,7 @@ func (*serveRolesStore) EdgeReader() (issueops.EdgeReader, error)
|
|||
func (*serveRolesStore) BlockingAnnotator() (issueops.BlockingAnnotator, error) { return nil, nil }
|
||||
func (*serveRolesStore) TreeWalker() (issueops.TreeWalker, error) { return nil, nil }
|
||||
func (*serveRolesStore) ReadyCounter() (issueops.ReadyCounter, error) { return nil, nil }
|
||||
func (*serveRolesStore) BlockedLister() (issueops.BlockedLister, error) { return nil, nil }
|
||||
func (*serveRolesStore) Querier() (issueops.Querier, error) { return nil, nil }
|
||||
func (*serveRolesStore) Sweeper() (issueops.Sweeper, error) { return nil, nil }
|
||||
func (*serveRolesStore) Deleter() (issueops.Deleter, error) { return nil, nil }
|
||||
|
|
|
|||
|
|
@ -223,6 +223,11 @@ func (*serveIdentityStore) LeaseReclaimer() (issueops.LeaseReclaimer, error) {
|
|||
func (*serveIdentityStore) Heartbeater() (issueops.Heartbeater, error) {
|
||||
return serveIdentityRole{}, nil
|
||||
}
|
||||
|
||||
// BlockedLister is declared at depth 1 for the same reason.
|
||||
func (*serveIdentityStore) BlockedLister() (issueops.BlockedLister, error) {
|
||||
return serveIdentityRole{}, nil
|
||||
}
|
||||
func (*serveIdentityStore) IssueLifecycle() (issueops.Lifecycle, error) {
|
||||
return serveIdentityRole{}, nil
|
||||
}
|
||||
|
|
@ -312,6 +317,7 @@ type serveIdentityRole struct {
|
|||
issueops.Releaser
|
||||
issueops.LeaseReclaimer
|
||||
issueops.Heartbeater
|
||||
issueops.BlockedLister
|
||||
issueops.ReadyClaimer
|
||||
issueops.BatchCloser
|
||||
issueops.MetadataCAS
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ This helps identify:
|
|||
days, _ := cmd.Flags().GetInt("days")
|
||||
status, _ := cmd.Flags().GetString("status")
|
||||
limit, _ := cmd.Flags().GetInt("limit")
|
||||
// Normalized for the reason blockedFilterFromFlags gives: these are
|
||||
// Normalized for the reason blockedRequestFromFlags gives: these are
|
||||
// exact-match clauses, and every sibling label filter trims its input
|
||||
// before building them.
|
||||
rawLabels, _ := cmd.Flags().GetStringSlice("label")
|
||||
|
|
|
|||
|
|
@ -163,6 +163,14 @@ is refused on both list operations with 400 `invalid_argument` /
|
|||
`reason: "invalid_value"`, whether or not a token is configured. Clients must
|
||||
page.
|
||||
|
||||
The blocked listing (`GET /v0/beads/blocked`, behind `blocked.list`) is the
|
||||
exception, on every bind: like `bd blocked`, it takes no `limit` and no cursor,
|
||||
so it answers the whole blocked set in one body. That set, not the whole active
|
||||
one, is what it buffers, and the client bounds what it will read (bd's HTTP
|
||||
client refuses a body over 32 MiB). The operation answers `has_more` so a
|
||||
later server can bound it; a client must refuse `has_more: true` rather than
|
||||
treat it as the whole listing.
|
||||
|
||||
## Probes
|
||||
|
||||
| Probe | Route | What green means |
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ the behavior.
|
|||
|
||||
## Summary
|
||||
|
||||
234 rows: 172 refuse, 35 degrade, 27 retired.
|
||||
234 rows: 171 refuse, 35 degrade, 28 retired.
|
||||
|
||||
## Whole-behavior divergences (D9 ledger)
|
||||
|
||||
|
|
@ -156,7 +156,7 @@ Whole commands, and the flag modes of served commands, that dispatch onto method
|
|||
| F-show-refs | refuse | `--refs` | `bd show --refs` refuses | showIssueRefs's --json marshals the full GetDependentsWithMetadata rows, but the wire answers the same collectDependents shallow projection, so created_at/assignee/description come back zeroed and the JSON differs from a local workspace. The text render consumes only the shallow fields, but the flag cannot be split from its --json mode, so the whole flag refuses rather than serve a divergent JSON silently | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
|
||||
| F-show-children | refuse | `--children` | `bd show --children` refuses | showIssueChildren's --json marshals the full GetDependentsWithMetadata rows, the same collectDependents shallow projection as --refs, so created_at/assignee/description come back zeroed over http. `bd children` is NOT this flag: it is a `bd list --parent` listing, served through the reader role (S6c) | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
|
||||
| F-mol-ready | refuse | — | `bd mol ready` refuses | it is the same runMolReadyGatedCore body as `bd ready --gated` | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
|
||||
| F-blocked | refuse | — | `bd blocked` refuses | it is raw GetBlockedIssues, which is on the unsupported allowlist | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
|
||||
| F-blocked | retired | — | RETIRED — `bd blocked` is SERVED whole | it said the command refuses because "it is raw GetBlockedIssues, which is on the unsupported allowlist", and that is no longer so: bd serve publishes listBlockedIssues (GET /v0/beads/blocked) behind blocked.list, over the issueops.BlockedLister role every leg implements, and `bd blocked` takes that role on every route, so the http client dials the one operation and prints the server's answer. Every listing flag the command publishes (--parent, --label, --label-any, --exclude-label) is a parameter of that operation. THE RAW FLAG IS THE EXCEPTION. --flags is not the listing: it reads listBlockingAnnotations with is_blocked, behind dependencies.blocking.isBlocked, and --flags --raw refuses before that read against a server that advertises policy.external_dependencies, as bd serve does on both arms because it composes its roles through the policy. That server's flag already carries the policy, and the v0 wire has no member that asks it for the stored column, so answering would print the decorated flag as the raw one (refuseRawFlagsFromAPolicyServer, cmd/bd/blocked_flags.go); the refusal names --flags, the policy-aware flag. Against a server that does not apply the policy its flag IS the column, and --raw is served. Against a server that does not advertise blocked.list the role refuses before the dial, naming the token: a capability refusal, not a divergence. The listing is unpaged and is one response body: an answer over the client's 32 MiB response limit is refused (wire.ResponseTooLargeError), and one reporting has_more is refused (TruncatedListingError), never returned short | D7 (RETIRED) | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
|
||||
| F-count | retired | — | RETIRED — `bd count` is SERVED whole | it said the command refuses because "issueops.Counter has no wire operation; a counts operation is a filed upstream ask", and that ask was DELIVERED: upstream #5508 published countIssues, client wave ga-icks1 wired the Counter accessor, and `count` moved from httpRefusedCommands into httpServedCommands. D8 row 20 and docs/reference/http-workspaces.md have said so since; this row was the last place that did not. Every flag the command publishes reaches a wire member — the whole predicate, the six instant bounds, the three emptiness checks, --include-infra, and the five --by-* flags as the one group_by parameter — so there is no refused mode left to name either. HOW IT ROTTED IS THE PART WORTH KEEPING. Its pin was TestClassifiedRefusedCommandsRefuseBeforeTheOSSPreRun, which walks httpRefusedCommands and drives every entry. The moment `count` left that table the pin stopped covering this row — it stayed LIVE BY NAME, so the well-formedness gate that resolves PinnedBy to a real test kept passing, and DEAD BY COVERAGE, so nothing anywhere asserted the row's claim. A ledger row can be false for a whole wave under a green pin, which is what TestFRowsAgreeWithTheCommandClassification now makes impossible | D7 (RETIRED), D8 row 20 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
|
||||
| F-serve | refuse | — | `bd serve` refuses against an http workspace | the OSS classifier would happily serve it from the opened store, and a bd serve re-serving a remote bd serve is a proxy chain nobody designed: run serve where the database is | D7 | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
|
||||
| F-close | refuse | — | `bd close` is SERVED whole — single id and several ids — over issues:batchClose; it refuses against a DOWN-LEVEL server that does not advertise issues.batchClose, and --claim-next refuses against every server, before anything closes | the CLI's close front door routes every id, single-id included, through BatchCloser.CloseBatch, and Lifecycle.Close has zero CLI callers at tip. The wire now carries issues:batchClose, so a CloseBatchRequest of any size is one wire call and one server-side transaction; nothing is composed or refused where the capability is present. THE NEXT CLAIM IS THE EXCEPTION. batchCloseIssues has no member to carry it, so the client refuses a ClaimNext on both legs, after the claim's own validation and before the dial (W-CloseBatchRequest.ClaimNext). Closing and then claiming would split the role's one transaction in two, and a claim that failed after the closes committed could not report them, because the role answers with an error or with outcomes, never both. On the CLI's chain the external-dependency decorator (design 3.6) refuses first unless the server advertises wire.CapExternalDependencies, and its refusal says nothing closed and names the commands that do the same work: close without --claim-next, then `bd ready --claim` (internal/storage/externaldeps/remote_roles.go). Against a server too old to advertise issues.batchClose, servesBatchClose() reads the handshake snapshot and routes around the batch dial entirely, so no Preflight runs and no wire.ErrCapabilityAbsent is raised: the down-level leg's refuseUnservedCloseShape raises the STORE's own *ErrHTTPUnsupported (batchcloser.go), which names the refused shape and the server, and cmd/bd prints it against each id the batch carried. The single-item, no-ClaimNext shape still composes onto closeIssue in that down-level leg (see L18); the shapes that cannot compose refuse there. The item cap is L-close-cap | D8 row 17 (resolved, Wire), D9 L18, D9 L-close-cap | TODO(S3): store/dial-seam and cmd/bd conformance this package's own gates do not reach; see the in-repo divergence ledger, engdocs/design/http-divergence-ledger.md, for the discipline |
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ go_library(
|
|||
"batch_close.go",
|
||||
"batch_create.go",
|
||||
"batch_get.go",
|
||||
"blocked.go",
|
||||
"blocking.go",
|
||||
"claim.go",
|
||||
"claim_next.go",
|
||||
|
|
@ -71,6 +72,7 @@ go_test(
|
|||
"batch_close_test.go",
|
||||
"batch_create_test.go",
|
||||
"batch_get_test.go",
|
||||
"blocked_test.go",
|
||||
"blocking_test.go",
|
||||
"brief_projection_test.go",
|
||||
"claim_next_test.go",
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
72
internal/httpapi/blocked.go
Normal file
72
internal/httpapi/blocked.go
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/steveyegge/beads/internal/httpapi/apigen"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// handleListBlocked answers GET /v0/beads/blocked: what `bd blocked` prints,
|
||||
// from the same role (issueops.BlockedLister).
|
||||
//
|
||||
// It decodes parameters and nothing else. The role normalizes the labels and
|
||||
// owns the set, the narrowing and the order, so this handler cannot answer a
|
||||
// different listing from the local command for the same request.
|
||||
func (s *Server) handleListBlocked(w http.ResponseWriter, r *http.Request) {
|
||||
q := newQuery(r.URL.Query())
|
||||
req := blockedFilters(q)
|
||||
if !s.acceptQuery(w, r, q) {
|
||||
return
|
||||
}
|
||||
|
||||
lister, err := s.blockedLister(r)
|
||||
if err != nil {
|
||||
s.failErr(w, r, err)
|
||||
return
|
||||
}
|
||||
result, err := lister.ListBlocked(r.Context(), req)
|
||||
if err != nil {
|
||||
s.failReadErr(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, apigen.BlockedPage{
|
||||
Items: wireBlocked(result.Items),
|
||||
// Always false: this operation takes no limit, so nothing truncates
|
||||
// the listing. Emitted because the document types it as required.
|
||||
HasMore: false,
|
||||
})
|
||||
}
|
||||
|
||||
// blockedFilters decodes the blocked listing's request: `bd blocked`'s four
|
||||
// flags, one parameter each. It is a function of its own so a test can drive
|
||||
// it over an empty query and read back the exact set of names it asks for.
|
||||
func blockedFilters(q *query) issueops.BlockedRequest {
|
||||
return issueops.BlockedRequest{
|
||||
ParentID: q.str("parent"),
|
||||
Labels: q.list("label"),
|
||||
LabelsAny: q.list("label_any"),
|
||||
ExcludeLabels: q.list("exclude_label"),
|
||||
}
|
||||
}
|
||||
|
||||
// wireBlocked projects the role's rows onto the generated envelope's element
|
||||
// type, an alias of the same struct. The document says `items` is an empty
|
||||
// array and never null, and a row's `blocked_by` is never null either; both
|
||||
// are made true here as well as by the role, so the wire's guarantee does not
|
||||
// rest on every implementation of it.
|
||||
func wireBlocked(items []*types.BlockedIssue) []apigen.BlockedIssue {
|
||||
out := make([]apigen.BlockedIssue, 0, len(items))
|
||||
for _, item := range items {
|
||||
if item == nil {
|
||||
continue
|
||||
}
|
||||
row := *item
|
||||
if row.BlockedBy == nil {
|
||||
row.BlockedBy = []string{}
|
||||
}
|
||||
out = append(out, row)
|
||||
}
|
||||
return out
|
||||
}
|
||||
150
internal/httpapi/blocked_test.go
Normal file
150
internal/httpapi/blocked_test.go
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// These cover the transport half of GET /v0/beads/blocked: the parameter
|
||||
// mapping, the refusals the handler raises itself and the projection. The set,
|
||||
// its narrowing and its order are issueops.BlockedLister's, pinned by
|
||||
// backend/conformance/blocked_lister_contract.go on every leg, the served one
|
||||
// included.
|
||||
|
||||
func newBlockedServer(t *testing.T, lister *roleBlockedLister) *testServer {
|
||||
t.Helper()
|
||||
return newTestServer(t, rolesConfig(Config{BlockedLister: lister}))
|
||||
}
|
||||
|
||||
// TestListBlockedMapsEveryParameter: each `bd blocked` flag's parameter
|
||||
// reaches the role as sent, labels repeated, and nothing else is set.
|
||||
func TestListBlockedMapsEveryParameter(t *testing.T) {
|
||||
lister := &roleBlockedLister{}
|
||||
ts := newBlockedServer(t, lister)
|
||||
|
||||
resp := ts.get(t, "/v0/beads/blocked?parent=bd-p&label=a&label=b&label_any=c&exclude_label=d&exclude_label=e")
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
calls := lister.blockedRequests()
|
||||
if len(calls) != 1 {
|
||||
t.Fatalf("role calls = %d, want 1", len(calls))
|
||||
}
|
||||
want := issueops.BlockedRequest{
|
||||
ParentID: "bd-p",
|
||||
Labels: []string{"a", "b"},
|
||||
LabelsAny: []string{"c"},
|
||||
ExcludeLabels: []string{"d", "e"},
|
||||
}
|
||||
if !reflect.DeepEqual(calls[0], want) {
|
||||
t.Fatalf("role request = %+v, want %+v", calls[0], want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListBlockedWithNoParametersAsksTheWholeSet: an empty query is the
|
||||
// unnarrowed listing.
|
||||
func TestListBlockedWithNoParametersAsksTheWholeSet(t *testing.T) {
|
||||
lister := &roleBlockedLister{}
|
||||
ts := newBlockedServer(t, lister)
|
||||
|
||||
resp := ts.get(t, "/v0/beads/blocked")
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
calls := lister.blockedRequests()
|
||||
if len(calls) != 1 || !reflect.DeepEqual(calls[0], issueops.BlockedRequest{}) {
|
||||
t.Fatalf("role requests = %+v, want one empty request", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListBlockedRefusesAnUnknownParameter: a parameter the operation does
|
||||
// not publish is a 400 naming it, and the role is never asked.
|
||||
func TestListBlockedRefusesAnUnknownParameter(t *testing.T) {
|
||||
lister := &roleBlockedLister{}
|
||||
ts := newBlockedServer(t, lister)
|
||||
|
||||
resp := ts.get(t, "/v0/beads/blocked?limit=5")
|
||||
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["reason"] != string(ReasonUnknownParameter) || body["param"] != "limit" {
|
||||
t.Errorf("problem = %v, want invalid_argument/unknown_parameter naming limit", body)
|
||||
}
|
||||
if n := len(lister.blockedRequests()); n != 0 {
|
||||
t.Errorf("role calls = %d, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListBlockedRefusesARepeatedParent: parent is single-valued.
|
||||
func TestListBlockedRefusesARepeatedParent(t *testing.T) {
|
||||
lister := &roleBlockedLister{}
|
||||
ts := newBlockedServer(t, lister)
|
||||
|
||||
resp := ts.get(t, "/v0/beads/blocked?parent=a&parent=b")
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
if n := len(lister.blockedRequests()); n != 0 {
|
||||
t.Errorf("role calls = %d, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListBlockedProjectsTheRows: each row reaches the wire with its
|
||||
// blockers and count, in the role's order; a nil row is dropped, a nil
|
||||
// blocker list is [] and has_more is false.
|
||||
func TestListBlockedProjectsTheRows(t *testing.T) {
|
||||
lister := &roleBlockedLister{result: issueops.BlockedResult{Items: []*types.BlockedIssue{
|
||||
{Issue: types.Issue{ID: "bd-2", Title: "two", Priority: 0}, BlockedByCount: 1, BlockedBy: []string{"bd-9"}},
|
||||
nil,
|
||||
{Issue: types.Issue{ID: "bd-1", Title: "one", Priority: 1}},
|
||||
}}}
|
||||
ts := newBlockedServer(t, lister)
|
||||
|
||||
resp := ts.get(t, "/v0/beads/blocked")
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
raw := readAll(t, resp)
|
||||
if !strings.Contains(raw, `"has_more":false`) {
|
||||
t.Errorf("body %s does not carry has_more false", raw)
|
||||
}
|
||||
if !strings.Contains(raw, `"blocked_by":[]`) {
|
||||
t.Errorf("body %s does not encode a nil blocker list as []", raw)
|
||||
}
|
||||
first := strings.Index(raw, `"id":"bd-2"`)
|
||||
second := strings.Index(raw, `"id":"bd-1"`)
|
||||
if first < 0 || second < 0 || first > second {
|
||||
t.Errorf("body %s does not carry bd-2 then bd-1", raw)
|
||||
}
|
||||
if !strings.Contains(raw, `"blocked_by":["bd-9"]`) || !strings.Contains(raw, `"blocked_by_count":1`) {
|
||||
t.Errorf("body %s lost bd-2's blockers", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListBlockedEmptyIsAnEmptyArray: nothing blocked is "items":[].
|
||||
func TestListBlockedEmptyIsAnEmptyArray(t *testing.T) {
|
||||
ts := newBlockedServer(t, &roleBlockedLister{})
|
||||
resp := ts.get(t, "/v0/beads/blocked")
|
||||
if raw := readAll(t, resp); !strings.Contains(raw, `"items":[]`) {
|
||||
t.Errorf("body %s, want items []", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListBlockedIsAdvertised: the route row carries blocked.list.
|
||||
func TestListBlockedIsAdvertised(t *testing.T) {
|
||||
found := false
|
||||
for _, c := range Capabilities() {
|
||||
if c == "blocked.list" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("Capabilities() = %v, want blocked.list", Capabilities())
|
||||
}
|
||||
}
|
||||
|
|
@ -353,6 +353,7 @@ var (
|
|||
_ uow.BatchGetterSource = timedProvider{}
|
||||
_ uow.LeaseReclaimerSource = timedProvider{}
|
||||
_ uow.HeartbeaterSource = timedProvider{}
|
||||
_ uow.BlockedListerSource = timedProvider{}
|
||||
_ uow.RelationsSource = timedProvider{}
|
||||
_ uow.CommenterSource = timedProvider{}
|
||||
_ uow.BlockingAnnotatorSource = timedProvider{}
|
||||
|
|
@ -489,6 +490,12 @@ func (p timedProvider) Heartbeater() (issueops.Heartbeater, error) {
|
|||
return uow.NewHeartbeater(p)
|
||||
}
|
||||
|
||||
// BlockedLister builds the blocked listing OVER THIS WRAPPER, for
|
||||
// IssueReader's reason: its unit of work lands in this request's uow_ms.
|
||||
func (p timedProvider) BlockedLister() (issueops.BlockedLister, error) {
|
||||
return uow.NewBlockedLister(p)
|
||||
}
|
||||
|
||||
// MoleculeStepper builds the advance-a-molecule role OVER THIS WRAPPER, so
|
||||
// every read and the claim it composes go through this wrapper's roles.
|
||||
func (p timedProvider) MoleculeStepper() (issueops.MoleculeStepper, error) {
|
||||
|
|
|
|||
|
|
@ -46,6 +46,9 @@ var (
|
|||
// `bd list` renders its decoration from.
|
||||
_ apigen.IssueBlocking = issueops.IssueBlocking{}
|
||||
|
||||
// The blocked row is the struct `bd blocked --json` marshals.
|
||||
_ apigen.BlockedIssue = types.BlockedIssue{}
|
||||
|
||||
// The journal record is pinned to neither internal/types nor a role package
|
||||
// but to the journal's own leaf: eventsjournal.Record is what
|
||||
// `bd events tail` prints one of per line, and the committed golden fixture
|
||||
|
|
@ -62,6 +65,7 @@ var (
|
|||
_ types.Issue = apigen.ClaimResponse{}.Issue
|
||||
_ types.Statistics = apigen.StatsResponse{}.Summary
|
||||
_ []issueops.Cycle = apigen.CyclesPage{}.Items
|
||||
_ []types.BlockedIssue = apigen.BlockedPage{}.Items
|
||||
_ []types.TreeNode = apigen.DependencyTreePage{}.Items
|
||||
|
||||
// The envelopes that are NOT pages resolve their items the same way and are
|
||||
|
|
|
|||
|
|
@ -560,6 +560,9 @@ const (
|
|||
// depth, a cycle policy and a node shape of its own.
|
||||
OpGetDependencyTree = "getDependencyTree"
|
||||
OpCountReadyWork = "countReadyWork"
|
||||
// OpListBlockedIssues lists the blocked issues with the blockers bd names
|
||||
// for each, behind issueops.BlockedLister: what `bd blocked` prints.
|
||||
OpListBlockedIssues = "listBlockedIssues"
|
||||
OpQueryIssues = "queryIssues"
|
||||
// OpCountIssues sizes a set the ISSUE listing describes, behind
|
||||
// issueops.Counter. It is a sibling of countReadyWork rather than a mode of
|
||||
|
|
@ -829,6 +832,10 @@ var operationCodes = map[string][]Code{
|
|||
// and can refuse them the same way. limit=0's mode-dependent refusal has no
|
||||
// analog here because there is no limit to pass.
|
||||
OpCountReadyWork: {CodeInvalidArgument, CodeUnauthenticated, CodeBusy, CodeDBUnavailable, CodeInternal},
|
||||
// The blocked listing has no page, so no cursor or unlimited-read refusal,
|
||||
// and no 404: nothing blocked is an empty list. Its 400s are the
|
||||
// transport's (an unknown parameter, a repeated `parent`).
|
||||
OpListBlockedIssues: {CodeInvalidArgument, CodeUnauthenticated, CodeBusy, CodeDBUnavailable, CodeInternal},
|
||||
// A cardinality has no page, so there is no cursor or unlimited-read
|
||||
// refusal. It has no 404 either: a predicate matching nothing is 0.
|
||||
//
|
||||
|
|
|
|||
|
|
@ -721,6 +721,11 @@ func (s *Server) acceptQuery(w http.ResponseWriter, r *http.Request, q *query) b
|
|||
// unlimited read buffers the whole active set and its JSON encoding inside one
|
||||
// shared process, which must not be reachable by arbitrary network peers.
|
||||
//
|
||||
// The blocked listing (handleListBlocked) never reaches this check: it takes
|
||||
// no limit at all, like `bd blocked`, so it answers its whole set on every
|
||||
// bind. That set is the blocked one, not the whole active one; see the
|
||||
// operation's description and engdocs/SERVE_RUNBOOK.md.
|
||||
//
|
||||
// The bind mode is deliberately NOT advertised in ContextResponse. A client
|
||||
// that wants an unlimited read asks for one and, on this 400, re-issues with
|
||||
// an explicit limit; it is a client-side fix, never a retry.
|
||||
|
|
|
|||
|
|
@ -218,6 +218,32 @@ func (h *roleHeartbeater) heartbeatRequests() []issueops.HeartbeatRequest {
|
|||
return append([]issueops.HeartbeatRequest(nil), h.calls...)
|
||||
}
|
||||
|
||||
// roleBlockedLister is the blocked listing of the store-shaped source, its own
|
||||
// fake for roleHeartbeater's reason: a separate role on a separate accessor.
|
||||
type roleBlockedLister struct {
|
||||
result issueops.BlockedResult
|
||||
err error
|
||||
|
||||
mu sync.Mutex
|
||||
calls []issueops.BlockedRequest
|
||||
}
|
||||
|
||||
func (l *roleBlockedLister) ListBlocked(_ context.Context, req issueops.BlockedRequest) (issueops.BlockedResult, error) {
|
||||
l.mu.Lock()
|
||||
l.calls = append(l.calls, req)
|
||||
l.mu.Unlock()
|
||||
if l.err != nil {
|
||||
return issueops.BlockedResult{}, l.err
|
||||
}
|
||||
return l.result, nil
|
||||
}
|
||||
|
||||
func (l *roleBlockedLister) blockedRequests() []issueops.BlockedRequest {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return append([]issueops.BlockedRequest(nil), l.calls...)
|
||||
}
|
||||
|
||||
// roleRelations is the single-anchor NEIGHBOR role of the store-shaped source,
|
||||
// its own fake beside roleEdgeReader for roleGraphCounter's reason: the two sit
|
||||
// on adjacent accessors and answer about the same edges, so one fake serving
|
||||
|
|
@ -1022,6 +1048,9 @@ func rolesConfig(cfg Config) Config {
|
|||
if cfg.Heartbeater == nil {
|
||||
cfg.Heartbeater = &roleHeartbeater{}
|
||||
}
|
||||
if cfg.BlockedLister == nil {
|
||||
cfg.BlockedLister = &roleBlockedLister{}
|
||||
}
|
||||
if cfg.Relations == nil {
|
||||
cfg.Relations = &roleRelations{}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -306,10 +306,12 @@ const CapIssuesCreateGates = "issues.create.gates"
|
|||
const CapIssuesUpdateGates = "issues.update.gates"
|
||||
|
||||
// CapExternalDependencies is the CONDITIONAL behavior capability announcing
|
||||
// that this server's ready, claim, claim-next, close, blocking-annotation and
|
||||
// dependency-tree operations already apply bd's external-dependency policy
|
||||
// (an issue blocked by an unsatisfied `external:<project>:<capability>`
|
||||
// dependency is not ready, not claimable and not closable without force). A
|
||||
// that this server's ready, blocked-listing, claim, claim-next, close,
|
||||
// blocking-annotation and dependency-tree operations already apply bd's
|
||||
// external-dependency policy (an issue blocked by an unsatisfied
|
||||
// `external:<project>:<capability>` dependency is not ready, not claimable and
|
||||
// not closable without force, and the blocked listing lists it with that
|
||||
// dependency among its blockers). A
|
||||
// client that sees it must pass those operations through untouched: running
|
||||
// the policy again on the client would judge it against the CLIENT machine's
|
||||
// project configuration and would turn the server's atomic claim-next into a
|
||||
|
|
@ -553,6 +555,14 @@ var routeTable = []route{
|
|||
implemented: true,
|
||||
handler: (*Server).handleCountReady,
|
||||
},
|
||||
{
|
||||
op: OpListBlockedIssues,
|
||||
method: http.MethodGet,
|
||||
pattern: "/v0/beads/blocked",
|
||||
capability: "blocked.list",
|
||||
implemented: true,
|
||||
handler: (*Server).handleListBlocked,
|
||||
},
|
||||
{
|
||||
op: OpListIssues,
|
||||
method: http.MethodGet,
|
||||
|
|
|
|||
|
|
@ -300,6 +300,12 @@ type Config struct {
|
|||
// holder is alive and writes only the lease row. Required on the same
|
||||
// terms as every field here.
|
||||
Heartbeater issueops.Heartbeater
|
||||
// BlockedLister is the blocked listing behind GET /v0/beads/blocked:
|
||||
// what `bd blocked` prints. It is a SEPARATE field from Reader because it
|
||||
// is a separate role: Reader.Ready lists the unblocked front, this lists
|
||||
// the blocked rows with the blockers bd names for each. Required on the
|
||||
// same terms as every field here.
|
||||
BlockedLister issueops.BlockedLister
|
||||
// Relations is the single-anchor neighbor read behind
|
||||
// GET /v0/beads/issues/{id}/related. It is a SEPARATE field from EdgeReader
|
||||
// for the reason issueops.EdgeReader's own doc gives at length: that role
|
||||
|
|
@ -450,6 +456,7 @@ type Server struct {
|
|||
issueBatchGetter issueops.BatchGetter
|
||||
issueReclaimer issueops.LeaseReclaimer
|
||||
issueHeartbeater issueops.Heartbeater
|
||||
issueBlocked issueops.BlockedLister
|
||||
issueRelations issueops.Relations
|
||||
issueCommenter issueops.Commenter
|
||||
issueBlocking issueops.BlockingAnnotator
|
||||
|
|
@ -664,6 +671,7 @@ func Listen(cfg Config) (*Server, error) {
|
|||
issueBatchGetter: cfg.BatchGetter,
|
||||
issueReclaimer: cfg.LeaseReclaimer,
|
||||
issueHeartbeater: cfg.Heartbeater,
|
||||
issueBlocked: cfg.BlockedLister,
|
||||
issueRelations: cfg.Relations,
|
||||
issueCommenter: cfg.Commenter,
|
||||
issueBlocking: cfg.BlockingAnnotator,
|
||||
|
|
@ -786,12 +794,12 @@ func Listen(cfg Config) (*Server, error) {
|
|||
// "all or nothing" would turn an honest condition into a special case inside
|
||||
// three functions. It is checked once, on its own, below.
|
||||
func sourceRoles(cfg Config) []any {
|
||||
return []any{cfg.Reader, cfg.Claimer, cfg.ReadyClaimer, cfg.Releaser, cfg.Lifecycle, cfg.BatchCloser, cfg.Settings, cfg.Stats, cfg.CycleDetector, cfg.EdgeReader, cfg.GraphCounter, cfg.BatchGetter, cfg.LeaseReclaimer, cfg.Heartbeater, cfg.Relations, cfg.Commenter, cfg.BlockingAnnotator, cfg.TreeWalker, cfg.ReadyCounter, cfg.Counter, cfg.Querier, cfg.Sweeper, cfg.Deleter, cfg.BatchCreator, cfg.DependencyEditor, cfg.BatchApplier, cfg.Memories, cfg.MetadataCAS}
|
||||
return []any{cfg.Reader, cfg.Claimer, cfg.ReadyClaimer, cfg.Releaser, cfg.Lifecycle, cfg.BatchCloser, cfg.Settings, cfg.Stats, cfg.CycleDetector, cfg.EdgeReader, cfg.GraphCounter, cfg.BatchGetter, cfg.LeaseReclaimer, cfg.Heartbeater, cfg.BlockedLister, cfg.Relations, cfg.Commenter, cfg.BlockingAnnotator, cfg.TreeWalker, cfg.ReadyCounter, cfg.Counter, cfg.Querier, cfg.Sweeper, cfg.Deleter, cfg.BatchCreator, cfg.DependencyEditor, cfg.BatchApplier, cfg.Memories, cfg.MetadataCAS}
|
||||
}
|
||||
|
||||
// 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, ReadyClaimer, Releaser, Lifecycle, BatchCloser, Settings, Stats, CycleDetector, EdgeReader, GraphCounter, BatchGetter, LeaseReclaimer, Heartbeater, Relations, Commenter, BlockingAnnotator, TreeWalker, ReadyCounter, Counter, Querier, Sweeper, Deleter, BatchCreator, DependencyEditor, BatchApplier, Memories and MetadataCAS"
|
||||
const roleSourceNames = "Reader, Claimer, ReadyClaimer, Releaser, Lifecycle, BatchCloser, Settings, Stats, CycleDetector, EdgeReader, GraphCounter, BatchGetter, LeaseReclaimer, Heartbeater, BlockedLister, Relations, Commenter, BlockingAnnotator, TreeWalker, ReadyCounter, Counter, Querier, Sweeper, Deleter, BatchCreator, DependencyEditor, BatchApplier, Memories and MetadataCAS"
|
||||
|
||||
func anyRoleSet(cfg Config) bool {
|
||||
return slices.ContainsFunc(sourceRoles(cfg), func(r any) bool { return r != nil })
|
||||
|
|
@ -1205,6 +1213,18 @@ func (s *Server) heartbeater(r *http.Request) (issueops.Heartbeater, error) {
|
|||
return src.Heartbeater()
|
||||
}
|
||||
|
||||
// blockedLister returns the blocked-listing surface for one request, on the
|
||||
// same terms as every role above and held by INTERFACE so
|
||||
// uow.BlockedListerSource is load-bearing rather than decorative. It goes out
|
||||
// unwrapped: wireBlocked drops a nil element rather than dereferencing it.
|
||||
func (s *Server) blockedLister(r *http.Request) (issueops.BlockedLister, error) {
|
||||
if s.provider == nil {
|
||||
return s.issueBlocked, nil
|
||||
}
|
||||
var src uow.BlockedListerSource = timedProvider{inner: s.provider, rec: requestInfo(r.Context())}
|
||||
return src.BlockedLister()
|
||||
}
|
||||
|
||||
// relations returns the single-anchor neighbor surface for one request, built
|
||||
// the same two ways as edgeReader above and held by INTERFACE so
|
||||
// uow.RelationsSource is load-bearing rather than decorative.
|
||||
|
|
|
|||
|
|
@ -261,13 +261,13 @@ info:
|
|||
|
||||
`Issue`, `IssueWithCounts`, `IssueDetails`,
|
||||
`IssueWithDependencyMetadata`, `TreeNode`, `Dependency`, `Comment`,
|
||||
`BondRef`, `Statistics`, `Cycle`, `CycleMember`, `IssueBlocking` and
|
||||
`EventRecord` are
|
||||
`BondRef`, `Statistics`, `Cycle`, `CycleMember`, `IssueBlocking`,
|
||||
`BlockedIssue` and `EventRecord` are
|
||||
pinned to the canonical Go structs (`x-go-type`), so the CLI's `--json`
|
||||
output and these response bodies are one compatibility domain and cannot
|
||||
drift apart. Changes to them are limited to NEW optional fields, and each
|
||||
addition must land with its entry in this document in the same change — a
|
||||
two-way JSON-tag bijection test, covering all thirteen, fails CI otherwise.
|
||||
two-way JSON-tag bijection test, covering all fourteen, fails CI otherwise.
|
||||
A breaking change to those shapes requires cutting `/v1`, not editing `/v0`.
|
||||
|
||||
|
||||
|
|
@ -692,6 +692,97 @@ paths:
|
|||
'503':
|
||||
$ref: '#/components/responses/Unavailable'
|
||||
|
||||
/v0/beads/blocked:
|
||||
get:
|
||||
operationId: listBlockedIssues
|
||||
summary: List blocked issues
|
||||
description: >-
|
||||
The blocked issues, each with the blockers bd names for it: what
|
||||
`bd blocked --json` prints, from the same role
|
||||
(`issueops.BlockedLister`). Items are `BlockedIssue`, the element type
|
||||
that command emits, so the two surfaces carry one shape.
|
||||
|
||||
|
||||
THE SET IS SEEDED FROM THE STORED, TRANSITIVE `is_blocked` FLAG on both
|
||||
planes (durable and ephemeral), with closed and pinned-status rows
|
||||
excluded and NO type exclusions, then NARROWED to rows bd can name a
|
||||
blocker for: an active `blocks`, `waits-for` or `conditional-blocks`
|
||||
target resident in this workspace that is neither closed nor pinned,
|
||||
else the parent. A row whose flag is set but which has neither is not
|
||||
listed. Where the server applies the external-dependency policy
|
||||
(`policy.external_dependencies`), an unsatisfied `external:` blocker is
|
||||
added to the row's `blocked_by`, and a row blocked only by such refs
|
||||
(neither closed nor pinned) is listed too, narrowed by the same
|
||||
`parent` and label filters as every other row.
|
||||
|
||||
|
||||
Ordered by priority ascending, then `created_at` descending, then id.
|
||||
|
||||
|
||||
THERE IS NO `limit` AND NO CURSOR, like the local command, and
|
||||
`has_more` is therefore always false in v0. The whole listing is one
|
||||
response body, and this server bounds it by nothing but the blocked
|
||||
set itself, so a client's own response-size limit is the effective
|
||||
bound (bd's HTTP client refuses a body over 32 MiB, loudly, rather than
|
||||
reading part of it). A client MUST refuse an answer with `has_more`
|
||||
true rather than treat it as the whole listing: a later server may
|
||||
bound the answer and say so there, and with no cursor there is nothing
|
||||
to page with. Available when the server advertises `blocked.list`.
|
||||
security:
|
||||
- bearerToken: []
|
||||
parameters:
|
||||
- name: parent
|
||||
in: query
|
||||
description: >-
|
||||
Only the parent's direct children (a parent-child edge) and ids
|
||||
under it in the dotted hierarchy, as `bd blocked --parent` narrows.
|
||||
schema:
|
||||
type: string
|
||||
- name: label
|
||||
in: query
|
||||
description: >-
|
||||
Labels that must ALL be present (AND). Each value is trimmed, and
|
||||
blank and repeated values are dropped, as `bd blocked --label` does.
|
||||
style: form
|
||||
explode: true
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
- name: label_any
|
||||
in: query
|
||||
description: Labels of which at least one must be present (OR).
|
||||
style: form
|
||||
explode: true
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
- name: exclude_label
|
||||
in: query
|
||||
description: Labels that must all be absent.
|
||||
style: form
|
||||
explode: true
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
responses:
|
||||
'200':
|
||||
description: The blocked issues, in the listing's order.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/BlockedPage'
|
||||
'400':
|
||||
$ref: '#/components/responses/InvalidArgument'
|
||||
'401':
|
||||
$ref: '#/components/responses/Unauthenticated'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalError'
|
||||
'503':
|
||||
$ref: '#/components/responses/Unavailable'
|
||||
|
||||
/v0/beads/dependencies/cycles:
|
||||
get:
|
||||
operationId: listDependencyCycles
|
||||
|
|
@ -7505,7 +7596,7 @@ components:
|
|||
# ---------------------------------------------------------------------
|
||||
# Pinned schemas.
|
||||
#
|
||||
# Each of the thirteen below is `x-go-type`-pinned to the canonical Go struct,
|
||||
# Each of the fourteen below is `x-go-type`-pinned to the canonical Go struct,
|
||||
# so the generator emits a type ALIAS and no mirror struct exists anywhere.
|
||||
# `types.Issue`'s JSON encoding IS this contract; the CLI's `--json`, the
|
||||
# JSONL interchange and these bodies all marshal the same struct.
|
||||
|
|
@ -7517,7 +7608,7 @@ components:
|
|||
# added to the Go struct without an entry here fails CI, and an entry here
|
||||
# with no Go field fails CI.
|
||||
#
|
||||
# Nine of the thirteen are pinned to `internal/types`. The other four are
|
||||
# Ten of the fourteen are pinned to `internal/types`. The other four are
|
||||
# pinned where their canonical struct actually lives: `CycleMember`,
|
||||
# `Cycle` and `IssueBlocking`, which appear after `Statistics`, to the role
|
||||
# package `issueops`; `EventRecord`, last of the group, to
|
||||
|
|
@ -8938,7 +9029,7 @@ components:
|
|||
The tokens this server advertises: the OPERATIONS it implements,
|
||||
derived from its route table, and the server-wide BEHAVIORS it
|
||||
enforces. v0's operation vocabulary is `ready.list`, `ready.count`,
|
||||
`issues.list`, `issues.query`, `issues.count`, `issues.get`,
|
||||
`blocked.list`, `issues.list`, `issues.query`, `issues.count`, `issues.get`,
|
||||
`issues.related`, `issues.create`, `issues.addComment`,
|
||||
`issues.batchClose`,
|
||||
`issues.claim`, `issues.claimNext`, `issues.release`,
|
||||
|
|
@ -9043,11 +9134,13 @@ components:
|
|||
see those parameters) rather than answering
|
||||
`unknown_parameter`. One behavior token is
|
||||
CONDITIONAL rather than build-level: `policy.external_dependencies`
|
||||
announces that this server's ready, claim, claim-next, close,
|
||||
blocking and dependency-tree operations already apply bd's
|
||||
external-dependency policy (an issue blocked by an unsatisfied
|
||||
`external:<project>:<capability>` dependency is neither ready,
|
||||
claimable nor closable without force). A server advertises it
|
||||
announces that this server's ready, blocked-listing, claim,
|
||||
claim-next, close, blocking and dependency-tree operations already
|
||||
apply bd's external-dependency policy (an issue blocked by an
|
||||
unsatisfied `external:<project>:<capability>` dependency is
|
||||
neither ready, claimable nor closable without force, and the
|
||||
blocked listing lists it with that dependency in its
|
||||
`blocked_by`). A server advertises it
|
||||
only when it enforces that policy; a client that sees it must not
|
||||
apply the policy again, and a client that does not see it applies
|
||||
the policy itself. The
|
||||
|
|
@ -9935,6 +10028,115 @@ components:
|
|||
True when the limit truncated the result. There is no cursor on
|
||||
this operation; narrow the filters or raise the limit.
|
||||
|
||||
BlockedIssue:
|
||||
type: object
|
||||
description: >-
|
||||
An `Issue` plus the blockers bd names for it. This is the element type
|
||||
of `/v0/beads/blocked`, matching what `bd blocked --json` emits.
|
||||
Property semantics are documented on `Issue`.
|
||||
x-go-type: types.BlockedIssue
|
||||
x-go-type-import:
|
||||
name: types
|
||||
path: github.com/steveyegge/beads/internal/types
|
||||
required:
|
||||
[id, title, priority, created_at, updated_at, blocked_by_count, blocked_by]
|
||||
properties:
|
||||
# --- repeated from Issue (see the pinned-schema note above) ---
|
||||
id: { type: string }
|
||||
title: { type: string }
|
||||
description: { type: string }
|
||||
design: { type: string }
|
||||
acceptance_criteria: { type: string }
|
||||
notes: { type: string }
|
||||
spec_id: { type: string }
|
||||
status: { type: string }
|
||||
priority: { type: integer }
|
||||
issue_type: { type: string }
|
||||
is_blocked: { type: boolean }
|
||||
assignee: { type: string }
|
||||
owner: { type: string }
|
||||
estimated_minutes: { type: integer }
|
||||
created_at: { type: string, format: date-time }
|
||||
created_by: { type: string }
|
||||
updated_at: { type: string, format: date-time }
|
||||
started_at: { type: string, format: date-time }
|
||||
closed_at: { type: string, format: date-time }
|
||||
close_reason: { type: string }
|
||||
closed_by_session: { type: string }
|
||||
lease_expires_at: { type: string, format: date-time }
|
||||
heartbeat_at: { type: string, format: date-time }
|
||||
lease_granted_node: { type: string }
|
||||
due_at: { type: string, format: date-time }
|
||||
defer_until: { type: string, format: date-time }
|
||||
external_ref: { type: string }
|
||||
source_system: { type: string }
|
||||
metadata: { type: object, additionalProperties: true }
|
||||
compaction_level: { type: integer }
|
||||
compacted_at: { type: string, format: date-time }
|
||||
compacted_at_commit: { type: string }
|
||||
original_size: { type: integer }
|
||||
labels: { type: array, items: { type: string } }
|
||||
dependencies:
|
||||
type: array
|
||||
items: { $ref: '#/components/schemas/Dependency' }
|
||||
comments:
|
||||
type: array
|
||||
description: >-
|
||||
The issue's comment bodies. On a listing they are populated only
|
||||
when the caller opts in (`bd list --include-comments`); absent
|
||||
otherwise, which is what `comment_count` and `comments_omitted`
|
||||
report about.
|
||||
items: { $ref: '#/components/schemas/Comment' }
|
||||
sender: { type: string }
|
||||
ephemeral: { type: boolean }
|
||||
no_history: { type: boolean }
|
||||
wisp_type: { type: string }
|
||||
storage_class: { type: string }
|
||||
pinned: { type: boolean }
|
||||
is_template: { type: boolean }
|
||||
bonded_from:
|
||||
type: array
|
||||
items: { $ref: '#/components/schemas/BondRef' }
|
||||
await_type: { type: string }
|
||||
await_id: { type: string }
|
||||
timeout: { type: integer, format: int64 }
|
||||
waiters: { type: array, items: { type: string } }
|
||||
source_formula: { type: string }
|
||||
source_location: { type: string }
|
||||
mol_type: { type: string }
|
||||
work_type: { type: string }
|
||||
event_kind: { type: string }
|
||||
actor: { type: string }
|
||||
target: { type: string }
|
||||
payload: { type: string }
|
||||
# --- added by BlockedIssue ---
|
||||
blocked_by_count:
|
||||
type: integer
|
||||
description: The length of `blocked_by`.
|
||||
blocked_by:
|
||||
type: array
|
||||
description: >-
|
||||
The ids bd names as this issue's blockers: its active blocking
|
||||
targets, else its parent, plus any unsatisfied `external:` refs
|
||||
where the external-dependency policy applies. Never null.
|
||||
items: { type: string }
|
||||
|
||||
BlockedPage:
|
||||
type: object
|
||||
required: [items, has_more]
|
||||
properties:
|
||||
items:
|
||||
type: array
|
||||
description: Empty array (never null) when nothing is blocked.
|
||||
items:
|
||||
$ref: '#/components/schemas/BlockedIssue'
|
||||
has_more:
|
||||
type: boolean
|
||||
description: >-
|
||||
Always false in v0: this operation takes no limit, so the listing
|
||||
is never truncated. Present so that adding a bound later is
|
||||
additive.
|
||||
|
||||
CyclesPage:
|
||||
type: object
|
||||
required: [items, has_more]
|
||||
|
|
@ -10166,7 +10368,7 @@ components:
|
|||
other. (Envelopes and page wrappers are unpinned as a class, for a
|
||||
different reason: they are new wire surface with no prior
|
||||
implementation. `TestWireTagBijection`'s `pinnedSchemas` is the
|
||||
authority on what is pinned.) The thirteen pinned schemas above are
|
||||
authority on what is pinned.) The fourteen pinned schemas above are
|
||||
pinned because a canonical Go struct already IS the contract —
|
||||
`types.Issue`'s JSON encoding is what `bd show --json` emits. A setting
|
||||
has no such struct: the CLI marshals an ad-hoc
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ import (
|
|||
// pinning.go proves those three are aliases; only this test proves the document
|
||||
// still describes them.
|
||||
// The import path is per-entry rather than one constant, because the canonical
|
||||
// structs do not all live in one package: nine are internal/types, and the
|
||||
// structs do not all live in one package: ten are internal/types, and the
|
||||
// three that are not — the cycle pair and IssueBlocking — live in the role
|
||||
// package issueops, where the results of issueops.CycleDetector and
|
||||
// issueops.BlockingAnnotator are declared, and EventRecord lives in
|
||||
|
|
@ -46,6 +46,7 @@ var pinnedSchemas = []struct {
|
|||
{"Comment", "types.Comment", canonicalTypesImport, types.Comment{}},
|
||||
{"BondRef", "types.BondRef", canonicalTypesImport, types.BondRef{}},
|
||||
{"Statistics", "types.Statistics", canonicalTypesImport, types.Statistics{}},
|
||||
{"BlockedIssue", "types.BlockedIssue", canonicalTypesImport, types.BlockedIssue{}},
|
||||
{"Cycle", "issueops.Cycle", canonicalRolesImport, issueops.Cycle{}},
|
||||
{"CycleMember", "issueops.CycleMember", canonicalRolesImport, issueops.CycleMember{}},
|
||||
{"IssueBlocking", "issueops.IssueBlocking", canonicalRolesImport, issueops.IssueBlocking{}},
|
||||
|
|
|
|||
418
internal/httpapi/wireshape/testdata/golden.json
vendored
418
internal/httpapi/wireshape/testdata/golden.json
vendored
|
|
@ -1174,6 +1174,383 @@
|
|||
"required": true,
|
||||
"item_type": "string"
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "acceptance_criteria",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "actor",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "assignee",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "await_id",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "await_type",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "blocked_by",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"item_type": "string"
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "blocked_by_count",
|
||||
"type": "integer",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "bonded_from",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"item_type": "object"
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "close_reason",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "closed_at",
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "closed_by_session",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "comments",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"item_type": "object"
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "compacted_at",
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "compacted_at_commit",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "compaction_level",
|
||||
"type": "integer",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "created_at",
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "created_by",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "defer_until",
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "dependencies",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"item_type": "object"
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "description",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "design",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "due_at",
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "ephemeral",
|
||||
"type": "boolean",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "estimated_minutes",
|
||||
"type": "integer",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "event_kind",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "external_ref",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "heartbeat_at",
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "id",
|
||||
"type": "string",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "is_blocked",
|
||||
"type": "boolean",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "is_template",
|
||||
"type": "boolean",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "issue_type",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "labels",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"item_type": "string"
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "lease_expires_at",
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "lease_granted_node",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "metadata",
|
||||
"type": "object",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "mol_type",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "no_history",
|
||||
"type": "boolean",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "notes",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "original_size",
|
||||
"type": "integer",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "owner",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "payload",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "pinned",
|
||||
"type": "boolean",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "priority",
|
||||
"type": "integer",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "sender",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "source_formula",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "source_location",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "source_system",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "spec_id",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "started_at",
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "status",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "storage_class",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "target",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "timeout",
|
||||
"type": "integer",
|
||||
"format": "int64",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "title",
|
||||
"type": "string",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "updated_at",
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "waiters",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"item_type": "string"
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "wisp_type",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedIssue",
|
||||
"member": "work_type",
|
||||
"type": "string",
|
||||
"required": false
|
||||
},
|
||||
{
|
||||
"schema": "BlockedPage",
|
||||
"member": "has_more",
|
||||
"type": "boolean",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"schema": "BlockedPage",
|
||||
"member": "items",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"item_type": "object"
|
||||
},
|
||||
{
|
||||
"schema": "Blocker",
|
||||
"member": "id",
|
||||
|
|
@ -5796,6 +6173,41 @@
|
|||
"required": true,
|
||||
"style": "simple"
|
||||
},
|
||||
{
|
||||
"schema": "param:listBlockedIssues",
|
||||
"member": "query:exclude_label",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"item_type": "string",
|
||||
"style": "form",
|
||||
"explode": true
|
||||
},
|
||||
{
|
||||
"schema": "param:listBlockedIssues",
|
||||
"member": "query:label",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"item_type": "string",
|
||||
"style": "form",
|
||||
"explode": true
|
||||
},
|
||||
{
|
||||
"schema": "param:listBlockedIssues",
|
||||
"member": "query:label_any",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"item_type": "string",
|
||||
"style": "form",
|
||||
"explode": true
|
||||
},
|
||||
{
|
||||
"schema": "param:listBlockedIssues",
|
||||
"member": "query:parent",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"style": "form",
|
||||
"explode": true
|
||||
},
|
||||
{
|
||||
"schema": "param:listBlockingAnnotations",
|
||||
"member": "query:is_blocked",
|
||||
|
|
@ -6681,6 +7093,12 @@
|
|||
"BatchGetIssuesRequest.ids[]": "request",
|
||||
"BatchGetIssuesResult": "response",
|
||||
"BatchGetIssuesResult.missing[]": "response",
|
||||
"BlockedIssue": "response",
|
||||
"BlockedIssue.blocked_by[]": "response",
|
||||
"BlockedIssue.labels[]": "response",
|
||||
"BlockedIssue.metadata": "response",
|
||||
"BlockedIssue.waiters[]": "response",
|
||||
"BlockedPage": "response",
|
||||
"Blocker": "response",
|
||||
"BlockingAnnotations": "response",
|
||||
"BondRef": "response",
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ go_library(
|
|||
"batchgetter.go",
|
||||
"blocked_querier.go",
|
||||
"blocked_recomputer.go",
|
||||
"blockedlister.go",
|
||||
"bridge.go",
|
||||
"ca.go",
|
||||
"ca_permissions_other.go",
|
||||
|
|
@ -100,6 +101,7 @@ go_test(
|
|||
"backend_credential_test.go",
|
||||
"batchapplier_test.go",
|
||||
"blocked_querier_test.go",
|
||||
"blockedlister_test.go",
|
||||
"brief_test.go",
|
||||
"bulk_roles_test.go",
|
||||
"ca_permissions_unix_test.go",
|
||||
|
|
@ -143,6 +145,8 @@ go_test(
|
|||
"served_batch_apply_test.go",
|
||||
"served_batch_close_test.go",
|
||||
"served_batch_getter_test.go",
|
||||
"served_blocked_external_test.go",
|
||||
"served_blocked_lister_test.go",
|
||||
"served_bridge_test.go",
|
||||
"served_bulk_test.go",
|
||||
"served_claim_lifecycle_test.go",
|
||||
|
|
|
|||
|
|
@ -402,3 +402,11 @@ func (s *Store) LeaseReclaimer() (issueops.LeaseReclaimer, error) {
|
|||
func (s *Store) Heartbeater() (issueops.Heartbeater, error) {
|
||||
return &httpHeartbeater{store: s}, nil
|
||||
}
|
||||
|
||||
// BlockedLister serves listBlockedIssues (GET /v0/beads/blocked), the
|
||||
// listing behind `bd blocked`. Store.dispatch preflights blocked.list, so an
|
||||
// older server is refused before the dial naming the token. See
|
||||
// blockedlister.go.
|
||||
func (s *Store) BlockedLister() (issueops.BlockedLister, error) {
|
||||
return &httpBlockedLister{store: s}, nil
|
||||
}
|
||||
|
|
|
|||
130
internal/httpclient/blockedlister.go
Normal file
130
internal/httpclient/blockedlister.go
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
package httpclient
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/steveyegge/beads/internal/httpapi/apigen"
|
||||
"github.com/steveyegge/beads/internal/httpclient/wire"
|
||||
storageops "github.com/steveyegge/beads/internal/storage/issueops"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// httpBlockedLister is issueops.BlockedLister over listBlockedIssues
|
||||
// (GET /v0/beads/blocked).
|
||||
//
|
||||
// It dials through Store.dispatch, so blocked.list is preflighted: a server
|
||||
// that does not advertise it is refused BEFORE the dial with
|
||||
// *wire.CapabilityError naming the token (it unwraps to
|
||||
// *storage.ErrUnsupported{Capability: "blocked.list"}). It never composes the
|
||||
// listing client-side from other reads: the set, its narrowing and its order
|
||||
// are the server's role's, in one transaction.
|
||||
//
|
||||
// The labels are sent normalized (storageops.BlockedFilter, the rule the
|
||||
// server's role applies again), so a blank or repeated value never reaches the
|
||||
// wire. The listing is a GET, so dispatch replays it on a busy answer.
|
||||
type httpBlockedLister struct{ store *Store }
|
||||
|
||||
var _ issueops.BlockedLister = (*httpBlockedLister)(nil)
|
||||
|
||||
func (l *httpBlockedLister) ListBlocked(ctx context.Context, req issueops.BlockedRequest) (issueops.BlockedResult, error) {
|
||||
var body apigen.BlockedPage
|
||||
if err := l.store.dispatch(ctx, wire.Request{
|
||||
Op: wire.OpListBlockedIssues,
|
||||
Method: http.MethodGet,
|
||||
Path: wire.PathBlocked,
|
||||
Query: blockedParams(req),
|
||||
}, &body); err != nil {
|
||||
return issueops.BlockedResult{}, err
|
||||
}
|
||||
// The listing is not a page, and this client has no cursor to follow. A
|
||||
// server that bounded the answer and said so (a later server may cap an
|
||||
// unpaged read) is refused rather than returned short: a caller reads a
|
||||
// missing row as an unblocked one.
|
||||
if body.HasMore {
|
||||
return issueops.BlockedResult{}, &TruncatedListingError{Op: wire.OpListBlockedIssues, Found: len(body.Items)}
|
||||
}
|
||||
items := make([]*types.BlockedIssue, 0, len(body.Items))
|
||||
for i := range body.Items {
|
||||
items = append(items, &body.Items[i])
|
||||
}
|
||||
return storageops.BlockedResultOf(items), nil
|
||||
}
|
||||
|
||||
// TruncatedListingError is the refusal of an unpaged listing the server
|
||||
// answered only in part: it returned Found rows and reported more remaining
|
||||
// (has_more). The operation publishes no cursor, so there is nothing to page
|
||||
// with, and returning the rows would be a silently short answer.
|
||||
type TruncatedListingError struct {
|
||||
// Op is the wire operation.
|
||||
Op string
|
||||
// Found is how many rows the server returned.
|
||||
Found int
|
||||
}
|
||||
|
||||
func (e *TruncatedListingError) Error() string {
|
||||
return fmt.Sprintf("%s over http: bd serve returned %d rows and reported more remaining; "+
|
||||
"the listing has no cursor, so this client refuses the truncated answer (narrow the request)",
|
||||
e.Op, e.Found)
|
||||
}
|
||||
|
||||
// blockedParams encodes the request as the operation's query: one parameter
|
||||
// per `bd blocked` flag, labels repeated, nothing sent for an empty field.
|
||||
func blockedParams(req issueops.BlockedRequest) url.Values {
|
||||
filter := storageops.BlockedFilter(req)
|
||||
params := url.Values{}
|
||||
if filter.ParentID != nil {
|
||||
params.Set("parent", *filter.ParentID)
|
||||
}
|
||||
for _, label := range filter.Labels {
|
||||
params.Add("label", label)
|
||||
}
|
||||
for _, label := range filter.LabelsAny {
|
||||
params.Add("label_any", label)
|
||||
}
|
||||
for _, label := range filter.ExcludeLabels {
|
||||
params.Add("exclude_label", label)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
// GetBlockedIssues is the legacy blocked read, answered by the role over the
|
||||
// wire, so a caller of the raw door gets the same listing `bd blocked` does.
|
||||
//
|
||||
// The role has no page and no row cap, and that is restated here rather than
|
||||
// dropped in silence: a filter carrying a Limit, an Offset or a MaxRows is
|
||||
// applied to the listing the server returned, exactly as the external-
|
||||
// dependency decorator applies them to the local one (finishBlockedIssues).
|
||||
// Every other WorkFilter field the legacy door never read stays unread.
|
||||
func (s *Store) GetBlockedIssues(ctx context.Context, filter types.WorkFilter) ([]*types.BlockedIssue, error) {
|
||||
req := issueops.BlockedRequest{
|
||||
Labels: filter.Labels,
|
||||
LabelsAny: filter.LabelsAny,
|
||||
ExcludeLabels: filter.ExcludeLabels,
|
||||
}
|
||||
if filter.ParentID != nil {
|
||||
req.ParentID = *filter.ParentID
|
||||
}
|
||||
result, err := (&httpBlockedLister{store: s}).ListBlocked(ctx, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := result.Items
|
||||
if filter.Offset > 0 {
|
||||
if filter.Offset >= len(items) {
|
||||
items = nil
|
||||
} else {
|
||||
items = items[filter.Offset:]
|
||||
}
|
||||
}
|
||||
if filter.Limit > 0 && len(items) > filter.Limit {
|
||||
items = items[:filter.Limit]
|
||||
}
|
||||
if err := storageops.EnforceMaxRowsCap(len(items), filter.MaxRows, filter.MaxRowsSource); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
230
internal/httpclient/blockedlister_test.go
Normal file
230
internal/httpclient/blockedlister_test.go
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
package httpclient
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/httpclient/wire"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// The unit half of the BlockedLister client leg: the preflight, the encoding
|
||||
// and the projection, over the real wire client against a doctored server.
|
||||
// The contract itself runs against a real bd serve in
|
||||
// served_blocked_lister_test.go.
|
||||
|
||||
type blockedStub struct {
|
||||
mu sync.Mutex
|
||||
queries []url.Values
|
||||
reply string
|
||||
}
|
||||
|
||||
func (b *blockedStub) store(t *testing.T, caps ...string) *Store {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == wire.PathContext {
|
||||
ctx := v0Context("proj-blk")
|
||||
ctx.Capabilities = caps
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(ctx)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodGet || r.URL.Path != wire.PathBlocked {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
b.mu.Lock()
|
||||
b.queries = append(b.queries, r.URL.Query())
|
||||
reply := b.reply
|
||||
b.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(reply))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
base, err := url.Parse(srv.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client, err := wire.New(base, nil, wire.Options{HTTPClient: srv.Client()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return New(Target{BaseURL: base}, client, nil)
|
||||
}
|
||||
|
||||
func (b *blockedStub) dials() []url.Values {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return append([]url.Values(nil), b.queries...)
|
||||
}
|
||||
|
||||
func blockedListerOf(t *testing.T, s *Store) issueops.BlockedLister {
|
||||
t.Helper()
|
||||
role, err := s.BlockedLister()
|
||||
if err != nil {
|
||||
t.Fatalf("BlockedLister(): %v", err)
|
||||
}
|
||||
return role
|
||||
}
|
||||
|
||||
// TestBlockedAgainstAServerWithoutTheTokenRefusesBeforeTheDial is the skew
|
||||
// row for a new client on an old server: no blocked.list in the handshake
|
||||
// means a case-2 refusal NAMING the token, with nothing sent, and never a
|
||||
// listing composed from other reads.
|
||||
func TestBlockedAgainstAServerWithoutTheTokenRefusesBeforeTheDial(t *testing.T) {
|
||||
stub := &blockedStub{reply: `{"items":[],"has_more":false}`}
|
||||
s := stub.store(t, "issues.list", "ready.list", "dependencies.blocking", "dependencies.list")
|
||||
|
||||
_, err := blockedListerOf(t, s).ListBlocked(t.Context(), issueops.BlockedRequest{})
|
||||
var capErr *wire.CapabilityError
|
||||
if !errors.As(err, &capErr) {
|
||||
t.Fatalf("ListBlocked on an old server = %v, want *wire.CapabilityError", err)
|
||||
}
|
||||
if capErr.Capability != "blocked.list" {
|
||||
t.Errorf("CapabilityError.Capability = %q, want blocked.list", capErr.Capability)
|
||||
}
|
||||
var unsupported *storage.ErrUnsupported
|
||||
if !errors.As(err, &unsupported) || unsupported.Capability != "blocked.list" {
|
||||
t.Errorf("ListBlocked on an old server = %v, want it to unwrap to *storage.ErrUnsupported{Capability: blocked.list}", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "blocked.list") {
|
||||
t.Errorf("the refusal %q does not name the token", err)
|
||||
}
|
||||
if n := len(stub.dials()); n != 0 {
|
||||
t.Errorf("%d blocked GETs reached an old server, want 0", n)
|
||||
}
|
||||
// The legacy door refuses the same way.
|
||||
if _, err := s.GetBlockedIssues(t.Context(), types.WorkFilter{}); !errors.As(err, &capErr) {
|
||||
t.Errorf("GetBlockedIssues on an old server = %v, want *wire.CapabilityError", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBlockedEncodesTheRequestNormalized: every field reaches its parameter,
|
||||
// labels repeated and normalized, nothing for an empty field.
|
||||
func TestBlockedEncodesTheRequestNormalized(t *testing.T) {
|
||||
stub := &blockedStub{reply: `{"items":[],"has_more":false}`}
|
||||
s := stub.store(t, "blocked.list")
|
||||
lister := blockedListerOf(t, s)
|
||||
|
||||
if _, err := lister.ListBlocked(t.Context(), issueops.BlockedRequest{
|
||||
ParentID: "bd-p",
|
||||
Labels: []string{" a ", "", "b", "a"},
|
||||
LabelsAny: []string{"c"},
|
||||
ExcludeLabels: []string{" d"},
|
||||
}); err != nil {
|
||||
t.Fatalf("ListBlocked: %v", err)
|
||||
}
|
||||
if _, err := lister.ListBlocked(t.Context(), issueops.BlockedRequest{}); err != nil {
|
||||
t.Fatalf("ListBlocked(empty): %v", err)
|
||||
}
|
||||
dials := stub.dials()
|
||||
if len(dials) != 2 {
|
||||
t.Fatalf("dials = %d, want 2", len(dials))
|
||||
}
|
||||
want := url.Values{"parent": {"bd-p"}, "label": {"a", "b"}, "label_any": {"c"}, "exclude_label": {"d"}}
|
||||
if !reflect.DeepEqual(dials[0], want) {
|
||||
t.Errorf("query = %v, want %v", dials[0], want)
|
||||
}
|
||||
if len(dials[1]) != 0 {
|
||||
t.Errorf("an empty request sent %v, want no parameters", dials[1])
|
||||
}
|
||||
}
|
||||
|
||||
// TestBlockedProjectsTheAnswer: rows come back as the server sent them, in
|
||||
// its order, never nil; an empty answer is an empty, non-nil slice.
|
||||
func TestBlockedProjectsTheAnswer(t *testing.T) {
|
||||
stub := &blockedStub{reply: `{"items":[` +
|
||||
`{"id":"bd-2","title":"two","priority":0,"created_at":"2026-10-16T01:00:00Z","updated_at":"2026-10-16T01:00:00Z","blocked_by_count":1,"blocked_by":["bd-9"]},` +
|
||||
`{"id":"bd-1","title":"one","priority":1,"created_at":"2026-10-16T01:00:00Z","updated_at":"2026-10-16T01:00:00Z","blocked_by_count":1,"blocked_by":["bd-2"]}` +
|
||||
`],"has_more":false}`}
|
||||
s := stub.store(t, "blocked.list")
|
||||
|
||||
result, err := blockedListerOf(t, s).ListBlocked(t.Context(), issueops.BlockedRequest{})
|
||||
if err != nil {
|
||||
t.Fatalf("ListBlocked: %v", err)
|
||||
}
|
||||
if len(result.Items) != 2 || result.Items[0].ID != "bd-2" || result.Items[1].ID != "bd-1" {
|
||||
t.Fatalf("items = %v, want bd-2 then bd-1", blockedRowIDs(result.Items))
|
||||
}
|
||||
if !reflect.DeepEqual(result.Items[0].BlockedBy, []string{"bd-9"}) || result.Items[0].BlockedByCount != 1 {
|
||||
t.Errorf("bd-2 = %+v, want blocked by bd-9", result.Items[0])
|
||||
}
|
||||
|
||||
stub.reply = `{"items":[],"has_more":false}`
|
||||
result, err = blockedListerOf(t, s).ListBlocked(t.Context(), issueops.BlockedRequest{})
|
||||
if err != nil {
|
||||
t.Fatalf("ListBlocked(empty): %v", err)
|
||||
}
|
||||
if result.Items == nil || len(result.Items) != 0 {
|
||||
t.Errorf("empty answer Items = %#v, want an empty non-nil slice", result.Items)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLegacyGetBlockedIssuesRidesTheRoleAndPages: the raw door dials the
|
||||
// role's operation and applies the filter's page to its answer.
|
||||
func TestLegacyGetBlockedIssuesRidesTheRoleAndPages(t *testing.T) {
|
||||
stub := &blockedStub{reply: `{"items":[` +
|
||||
`{"id":"bd-1","title":"a","priority":0,"created_at":"2026-10-16T01:00:00Z","updated_at":"2026-10-16T01:00:00Z","blocked_by_count":1,"blocked_by":["x"]},` +
|
||||
`{"id":"bd-2","title":"b","priority":1,"created_at":"2026-10-16T01:00:00Z","updated_at":"2026-10-16T01:00:00Z","blocked_by_count":1,"blocked_by":["x"]},` +
|
||||
`{"id":"bd-3","title":"c","priority":2,"created_at":"2026-10-16T01:00:00Z","updated_at":"2026-10-16T01:00:00Z","blocked_by_count":1,"blocked_by":["x"]}` +
|
||||
`],"has_more":false}`}
|
||||
s := stub.store(t, "blocked.list")
|
||||
parent := "bd-p"
|
||||
|
||||
got, err := s.GetBlockedIssues(t.Context(), types.WorkFilter{ParentID: &parent, Labels: []string{"l"}, Offset: 1, Limit: 1})
|
||||
if err != nil {
|
||||
t.Fatalf("GetBlockedIssues: %v", err)
|
||||
}
|
||||
if ids := blockedRowIDs(got); !reflect.DeepEqual(ids, []string{"bd-2"}) {
|
||||
t.Errorf("page = %v, want [bd-2]", ids)
|
||||
}
|
||||
dials := stub.dials()
|
||||
if len(dials) != 1 || dials[0].Get("parent") != "bd-p" || dials[0].Get("label") != "l" {
|
||||
t.Errorf("dials = %v, want one carrying parent and label", dials)
|
||||
}
|
||||
if _, err := s.GetBlockedIssues(t.Context(), types.WorkFilter{MaxRows: 2, MaxRowsSource: "--max-rows"}); err == nil {
|
||||
t.Errorf("GetBlockedIssues over its row cap answered, want the cap's refusal")
|
||||
}
|
||||
}
|
||||
|
||||
func blockedRowIDs(items []*types.BlockedIssue) []string {
|
||||
ids := make([]string, 0, len(items))
|
||||
for _, item := range items {
|
||||
ids = append(ids, item.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// TestBlockedRefusesAServerThatReportsMore: the listing has no cursor, so a
|
||||
// server that answers part of it with has_more is refused with a typed error,
|
||||
// never returned as a short listing a caller would read as complete.
|
||||
func TestBlockedRefusesAServerThatReportsMore(t *testing.T) {
|
||||
stub := &blockedStub{reply: `{"items":[` +
|
||||
`{"id":"bd-1","title":"a","priority":0,"created_at":"2026-10-16T01:00:00Z","updated_at":"2026-10-16T01:00:00Z","blocked_by_count":1,"blocked_by":["x"]}` +
|
||||
`],"has_more":true}`}
|
||||
s := stub.store(t, "blocked.list")
|
||||
|
||||
result, err := blockedListerOf(t, s).ListBlocked(t.Context(), issueops.BlockedRequest{})
|
||||
var truncated *TruncatedListingError
|
||||
if !errors.As(err, &truncated) {
|
||||
t.Fatalf("ListBlocked with has_more = %d items, err %v; want *TruncatedListingError", len(result.Items), err)
|
||||
}
|
||||
if truncated.Found != 1 || truncated.Op != wire.OpListBlockedIssues {
|
||||
t.Errorf("TruncatedListingError = %+v, want Op %s and Found 1", truncated, wire.OpListBlockedIssues)
|
||||
}
|
||||
if result.Items != nil {
|
||||
t.Errorf("a refused listing returned %d rows", len(result.Items))
|
||||
}
|
||||
if _, err := s.GetBlockedIssues(t.Context(), types.WorkFilter{}); !errors.As(err, &truncated) {
|
||||
t.Errorf("GetBlockedIssues with has_more: err %v, want *TruncatedListingError", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -251,7 +251,6 @@ var legitimatelyUnsupported = map[string]string{
|
|||
// refuse on these, which is why they are named in D7's refused class.
|
||||
"DetectCycles": "raw read: role CycleDetector serves this shape",
|
||||
"FindWispDependentsRecursive": "raw read: no recursive-dependents operation",
|
||||
"GetBlockedIssues": "raw read: no blocked-set operation (`bd blocked`)",
|
||||
"GetBlockingInfoForIssues": "raw read: role BlockingAnnotator serves this shape",
|
||||
"GetDependencies": "raw read: role EdgeReader serves this shape",
|
||||
"GetDependencyCounts": "raw read: the paired blocks-only batch, expressible as two GraphCounter calls with Types set to the blocking type — the role's own leaf declines to name it as a third method, and re-routing it here would invent the map-of-two-numbers shape no wire operation carries",
|
||||
|
|
|
|||
|
|
@ -1113,8 +1113,16 @@ func commandRows() []Row {
|
|||
"showIssueChildren's --json marshals the full GetDependentsWithMetadata rows, the same collectDependents shallow projection as --refs, so created_at/assignee/description come back zeroed over http. `bd children` is NOT this flag: it is a `bd list --parent` listing, served through the reader role (S6c)"),
|
||||
row("F-mol-ready", "mol ready", "", "`bd mol ready` refuses",
|
||||
"it is the same runMolReadyGatedCore body as `bd ready --gated`"),
|
||||
row("F-blocked", "blocked", "", "`bd blocked` refuses",
|
||||
"it is raw GetBlockedIssues, which is on the unsupported allowlist"),
|
||||
{
|
||||
ID: "F-blocked", Kind: KindRetired, Command: "blocked",
|
||||
What: "RETIRED — `bd blocked` is SERVED whole",
|
||||
Why: "it said the command refuses because \"it is raw GetBlockedIssues, which is on the unsupported allowlist\", and that is no longer so: bd serve publishes listBlockedIssues (GET /v0/beads/blocked) behind blocked.list, over the issueops.BlockedLister role every leg implements, and `bd blocked` takes that role on every route, so the http client dials the one operation and prints the server's answer. Every listing flag the command publishes (--parent, --label, --label-any, --exclude-label) is a parameter of that operation. THE RAW FLAG IS THE EXCEPTION. --flags is not the listing: it reads listBlockingAnnotations with is_blocked, behind dependencies.blocking.isBlocked, and --flags --raw refuses before that read against a server that advertises policy.external_dependencies, as bd serve does on both arms because it composes its roles through the policy. That server's flag already carries the policy, and the v0 wire has no member that asks it for the stored column, so answering would print the decorated flag as the raw one (refuseRawFlagsFromAPolicyServer, cmd/bd/blocked_flags.go); the refusal names --flags, the policy-aware flag. Against a server that does not apply the policy its flag IS the column, and --raw is served. Against a server that does not advertise blocked.list the role refuses before the dial, naming the token: a capability refusal, not a divergence. The listing is unpaged and is one response body: an answer over the client's 32 MiB response limit is refused (wire.ResponseTooLargeError), and one reporting has_more is refused (TruncatedListingError), never returned short",
|
||||
SpecRow: "D7 (RETIRED)",
|
||||
// The retirement's own evidence: the corpus replay and
|
||||
// TestE2E_BlockedOverHTTP compare `bd blocked --json` over http
|
||||
// against the same command over a local workspace.
|
||||
PinnedBy: pinnedByS3Conformance,
|
||||
},
|
||||
{
|
||||
ID: "F-count", Kind: KindRetired, Command: "count",
|
||||
What: "RETIRED — `bd count` is SERVED whole",
|
||||
|
|
|
|||
|
|
@ -73,6 +73,7 @@ func startOracle(t *testing.T) *oracle {
|
|||
BatchGetter: stubBatchGetter{},
|
||||
LeaseReclaimer: stubLeaseReclaimer{},
|
||||
Heartbeater: stubHeartbeater{},
|
||||
BlockedLister: stubBlockedLister{},
|
||||
Relations: stubRelations{},
|
||||
Commenter: stubCommenter{},
|
||||
BlockingAnnotator: stubBlocking{},
|
||||
|
|
@ -274,6 +275,7 @@ type (
|
|||
stubBatchGetter struct{ issueops.BatchGetter }
|
||||
stubLeaseReclaimer struct{ issueops.LeaseReclaimer }
|
||||
stubHeartbeater struct{ issueops.Heartbeater }
|
||||
stubBlockedLister struct{ issueops.BlockedLister }
|
||||
stubRelations struct{ issueops.Relations }
|
||||
stubCommenter struct{ issueops.Commenter }
|
||||
stubBlocking struct{ issueops.BlockingAnnotator }
|
||||
|
|
|
|||
283
internal/httpclient/served_blocked_external_test.go
Normal file
283
internal/httpclient/served_blocked_external_test.go
Normal file
|
|
@ -0,0 +1,283 @@
|
|||
//go:build cgo
|
||||
|
||||
package httpclient
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/httpapi"
|
||||
"github.com/steveyegge/beads/internal/storage/externaldeps"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// lazyBlockedLister defers building the server's blocked lister until the
|
||||
// first request, because the served harness opens the reference store only
|
||||
// after its config options have run.
|
||||
type lazyBlockedLister struct {
|
||||
get func() (issueops.BlockedLister, error)
|
||||
}
|
||||
|
||||
func (l lazyBlockedLister) ListBlocked(ctx context.Context, req issueops.BlockedRequest) (issueops.BlockedResult, error) {
|
||||
lister, err := l.get()
|
||||
if err != nil {
|
||||
return issueops.BlockedResult{}, err
|
||||
}
|
||||
return lister.ListBlocked(ctx, req)
|
||||
}
|
||||
|
||||
// newPolicyServedEnv is a served workspace composed the way `bd serve` composes
|
||||
// its store-shaped source: the blocked lister comes from the
|
||||
// external-dependency decorator over the reference store
|
||||
// (externaldeps.Store.BlockedLister), and the handshake advertises
|
||||
// policy.external_dependencies because that layer is really there
|
||||
// (externaldeps.Applied).
|
||||
func newPolicyServedEnv(t *testing.T, prefix string) *servedEnv {
|
||||
t.Helper()
|
||||
var env *servedEnv
|
||||
env = newServedEnv(t, prefix, func(cfg *httpapi.Config) {
|
||||
cfg.ExternalDependencyPolicy = true
|
||||
cfg.BlockedLister = lazyBlockedLister{get: func() (issueops.BlockedLister, error) {
|
||||
decorated := externaldeps.New(env.reference, nil, nil)
|
||||
if !externaldeps.Applied(decorated) {
|
||||
t.Errorf("the server's store is not composed through the external-dependency policy")
|
||||
}
|
||||
return decorated.BlockedLister()
|
||||
}}
|
||||
})
|
||||
return env
|
||||
}
|
||||
|
||||
// seedExternalBlocked seeds a local blocker, a row blocked by it AND an
|
||||
// unsatisfied external ref (mixed), a row blocked ONLY by an external ref, and
|
||||
// a free row. It returns the listing every route must answer.
|
||||
func seedExternalBlocked(t *testing.T, env *servedEnv) map[string][]string {
|
||||
t.Helper()
|
||||
ctx := t.Context()
|
||||
p := env.prefix
|
||||
for i, id := range []string{"blocker", "mixed", "extonly", "free"} {
|
||||
if err := env.createIssue(ctx, &types.Issue{
|
||||
ID: p + "-" + id, Title: id, Status: types.StatusOpen, Priority: i, IssueType: types.TypeTask,
|
||||
}, "seed"); err != nil {
|
||||
t.Fatalf("seed %s: %v", id, err)
|
||||
}
|
||||
}
|
||||
for _, dep := range []*types.Dependency{
|
||||
{IssueID: p + "-mixed", DependsOnID: p + "-blocker", Type: types.DepBlocks},
|
||||
{IssueID: p + "-mixed", DependsOnID: "external:otherproj:billing", Type: types.DepBlocks},
|
||||
{IssueID: p + "-extonly", DependsOnID: "external:otherproj:payments", Type: types.DepBlocks},
|
||||
} {
|
||||
if err := env.addDependency(ctx, dep, "seed"); err != nil {
|
||||
t.Fatalf("seed %s -> %s: %v", dep.IssueID, dep.DependsOnID, err)
|
||||
}
|
||||
}
|
||||
want := map[string][]string{
|
||||
p + "-mixed": {"external:otherproj:billing", p + "-blocker"},
|
||||
p + "-extonly": {"external:otherproj:payments"},
|
||||
}
|
||||
for _, blockers := range want {
|
||||
slices.Sort(blockers)
|
||||
}
|
||||
return want
|
||||
}
|
||||
|
||||
func blockedRowsByID(t *testing.T, items []*types.BlockedIssue) map[string][]string {
|
||||
t.Helper()
|
||||
got := map[string][]string{}
|
||||
for _, item := range items {
|
||||
blockers := slices.Clone(item.BlockedBy)
|
||||
slices.Sort(blockers)
|
||||
got[item.ID] = blockers
|
||||
if item.BlockedByCount != len(item.BlockedBy) {
|
||||
t.Errorf("%s: BlockedByCount = %d, len(BlockedBy) = %d", item.ID, item.BlockedByCount, len(item.BlockedBy))
|
||||
}
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
// TestServedBlockedListerCarriesExternalRefsWhenTheServerEnforces pins the
|
||||
// server-side decoration: against a server that advertises
|
||||
// policy.external_dependencies, the operation's own answer (the raw client
|
||||
// role, no client decoration at all) already lists the external-only row and
|
||||
// names the external ref on the mixed row, and the client's decorated chain,
|
||||
// which stands down to that server, answers the same.
|
||||
func TestServedBlockedListerCarriesExternalRefsWhenTheServerEnforces(t *testing.T) {
|
||||
env := newPolicyServedEnv(t, "bxe")
|
||||
want := seedExternalBlocked(t, env)
|
||||
ctx := t.Context()
|
||||
|
||||
if enforced, err := env.subject.ServerEnforcesExternalDependencyPolicy(ctx); err != nil || !enforced {
|
||||
t.Fatalf("ServerEnforcesExternalDependencyPolicy = %v, %v; want true", enforced, err)
|
||||
}
|
||||
|
||||
raw, err := env.subject.BlockedLister()
|
||||
if err != nil {
|
||||
t.Fatalf("BlockedLister: %v", err)
|
||||
}
|
||||
served, err := raw.ListBlocked(ctx, issueops.BlockedRequest{})
|
||||
if err != nil {
|
||||
t.Fatalf("raw ListBlocked: %v", err)
|
||||
}
|
||||
if got := blockedRowsByID(t, served.Items); !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("the server's own listing = %v, want %v (external refs decorated server-side)", got, want)
|
||||
}
|
||||
|
||||
chain, err := externaldeps.New(env.subject, nil, nil).BlockedLister()
|
||||
if err != nil {
|
||||
t.Fatalf("decorated BlockedLister: %v", err)
|
||||
}
|
||||
decorated, err := chain.ListBlocked(ctx, issueops.BlockedRequest{})
|
||||
if err != nil {
|
||||
t.Fatalf("decorated ListBlocked: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(decorated.Items, served.Items) {
|
||||
t.Errorf("the client's decorated chain answered %v, want the server's listing %v unchanged",
|
||||
blockedRowsByID(t, decorated.Items), want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestServedLegacyGetBlockedIssuesThroughTheDecorator pins the legacy blocked
|
||||
// door on the CLI's chain (externaldeps over the http store), which `bd ready
|
||||
// --explain`, `bd mol stale` and the wisp commands read through. It used to
|
||||
// fail over http on the raw multi-id read the decoration makes; it now takes
|
||||
// the served roles, against a server that applies the policy and one that
|
||||
// does not, and answers the same listing as the role, paged as asked.
|
||||
func TestServedLegacyGetBlockedIssuesThroughTheDecorator(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
env func(*testing.T) *servedEnv
|
||||
enforced bool
|
||||
}{
|
||||
{"server enforces", func(t *testing.T) *servedEnv { return newPolicyServedEnv(t, "bxl") }, true},
|
||||
{"client enforces", func(t *testing.T) *servedEnv { return newServedEnv(t, "bxm") }, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
env := tc.env(t)
|
||||
want := seedExternalBlocked(t, env)
|
||||
ctx := t.Context()
|
||||
if enforced, err := env.subject.ServerEnforcesExternalDependencyPolicy(ctx); err != nil || enforced != tc.enforced {
|
||||
t.Fatalf("ServerEnforcesExternalDependencyPolicy = %v, %v; want %v", enforced, err, tc.enforced)
|
||||
}
|
||||
decorated := externaldeps.New(env.subject, nil, nil)
|
||||
got, err := decorated.GetBlockedIssues(ctx, types.WorkFilter{})
|
||||
if err != nil {
|
||||
t.Fatalf("GetBlockedIssues over http: %v", err)
|
||||
}
|
||||
if rows := blockedRowsByID(t, got); !reflect.DeepEqual(rows, want) {
|
||||
t.Fatalf("GetBlockedIssues = %v, want %v", rows, want)
|
||||
}
|
||||
page, err := decorated.GetBlockedIssues(ctx, types.WorkFilter{Limit: 1})
|
||||
if err != nil {
|
||||
t.Fatalf("GetBlockedIssues(Limit=1): %v", err)
|
||||
}
|
||||
if len(page) != 1 || page[0].ID != got[0].ID {
|
||||
t.Errorf("GetBlockedIssues(Limit=1) = %v, want the first row %s", blockedRowsByID(t, page), got[0].ID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestServedBlockedListingFiltersExternalOnlyRowsByLabel pins the label filters
|
||||
// on the rows the decoration lists itself (blocked by nothing but an
|
||||
// unsatisfied external ref), which the listing's label query never saw: they
|
||||
// are judged by the same labels, wherever the policy is applied (the server's
|
||||
// decorator when the server advertises it, the client's otherwise), through
|
||||
// the role and the legacy door alike. A labelled row blocked locally rides
|
||||
// along, the query's own answer to the same filter.
|
||||
func TestServedBlockedListingFiltersExternalOnlyRowsByLabel(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
env func(*testing.T) *servedEnv
|
||||
enforced bool
|
||||
}{
|
||||
{"server enforces", func(t *testing.T) *servedEnv { return newPolicyServedEnv(t, "bxs") }, true},
|
||||
{"client enforces", func(t *testing.T) *servedEnv { return newServedEnv(t, "bxc") }, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
env := tc.env(t)
|
||||
ctx := t.Context()
|
||||
if enforced, err := env.subject.ServerEnforcesExternalDependencyPolicy(ctx); err != nil || enforced != tc.enforced {
|
||||
t.Fatalf("ServerEnforcesExternalDependencyPolicy = %v, %v; want %v", enforced, err, tc.enforced)
|
||||
}
|
||||
p := env.prefix
|
||||
for i, seed := range []struct {
|
||||
id string
|
||||
labels []string
|
||||
}{
|
||||
{"blocker", nil},
|
||||
{"local", []string{"lane:a"}},
|
||||
{"tagged", []string{"lane:a", "team:x"}},
|
||||
{"bare", nil},
|
||||
} {
|
||||
if err := env.createIssue(ctx, &types.Issue{
|
||||
ID: p + "-" + seed.id, Title: seed.id, Status: types.StatusOpen, Priority: i,
|
||||
IssueType: types.TypeTask, Labels: seed.labels,
|
||||
}, "seed"); err != nil {
|
||||
t.Fatalf("seed %s: %v", seed.id, err)
|
||||
}
|
||||
}
|
||||
for _, dep := range []*types.Dependency{
|
||||
{IssueID: p + "-local", DependsOnID: p + "-blocker", Type: types.DepBlocks},
|
||||
{IssueID: p + "-tagged", DependsOnID: "external:otherproj:payments", Type: types.DepBlocks},
|
||||
{IssueID: p + "-bare", DependsOnID: "external:otherproj:billing", Type: types.DepBlocks},
|
||||
} {
|
||||
if err := env.addDependency(ctx, dep, "seed"); err != nil {
|
||||
t.Fatalf("seed %s -> %s: %v", dep.IssueID, dep.DependsOnID, err)
|
||||
}
|
||||
}
|
||||
|
||||
decorated := externaldeps.New(env.subject, nil, nil)
|
||||
lister, err := decorated.BlockedLister()
|
||||
if err != nil {
|
||||
t.Fatalf("decorated BlockedLister: %v", err)
|
||||
}
|
||||
for _, fc := range []struct {
|
||||
name string
|
||||
req issueops.BlockedRequest
|
||||
want []string
|
||||
}{
|
||||
{"no filter", issueops.BlockedRequest{}, []string{"bare", "local", "tagged"}},
|
||||
{"label", issueops.BlockedRequest{Labels: []string{"lane:a"}}, []string{"local", "tagged"}},
|
||||
{"labels are all required", issueops.BlockedRequest{Labels: []string{"lane:a", "team:x"}}, []string{"tagged"}},
|
||||
{"label any", issueops.BlockedRequest{LabelsAny: []string{"lane:b", "team:x"}}, []string{"tagged"}},
|
||||
{"exclude label", issueops.BlockedRequest{ExcludeLabels: []string{"lane:a"}}, []string{"bare"}},
|
||||
{"label matching none", issueops.BlockedRequest{Labels: []string{"no-such-label"}}, []string{}},
|
||||
} {
|
||||
t.Run(fc.name, func(t *testing.T) {
|
||||
want := make([]string, 0, len(fc.want))
|
||||
for _, id := range fc.want {
|
||||
want = append(want, p+"-"+id)
|
||||
}
|
||||
res, err := lister.ListBlocked(ctx, fc.req)
|
||||
if err != nil {
|
||||
t.Fatalf("ListBlocked: %v", err)
|
||||
}
|
||||
if got := sortedBlockedIDs(res.Items); !slices.Equal(got, want) {
|
||||
t.Errorf("ListBlocked(%+v) = %v, want %v", fc.req, got, want)
|
||||
}
|
||||
legacy, err := decorated.GetBlockedIssues(ctx, types.WorkFilter{
|
||||
Labels: fc.req.Labels, LabelsAny: fc.req.LabelsAny, ExcludeLabels: fc.req.ExcludeLabels,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("GetBlockedIssues: %v", err)
|
||||
}
|
||||
if got := sortedBlockedIDs(legacy); !slices.Equal(got, want) {
|
||||
t.Errorf("GetBlockedIssues(%+v) = %v, want %v", fc.req, got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func sortedBlockedIDs(items []*types.BlockedIssue) []string {
|
||||
ids := make([]string, 0, len(items))
|
||||
for _, item := range items {
|
||||
ids = append(ids, item.ID)
|
||||
}
|
||||
slices.Sort(ids)
|
||||
return ids
|
||||
}
|
||||
24
internal/httpclient/served_blocked_lister_test.go
Normal file
24
internal/httpclient/served_blocked_lister_test.go
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
package httpclient
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/backend/conformance"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// TestServedBlockedListerContract runs the BlockedLister contract against a
|
||||
// real bd serve through this client's own BlockedLister accessor: the role
|
||||
// dialed over listBlockedIssues must answer what the store legs answer.
|
||||
func TestServedBlockedListerContract(t *testing.T) {
|
||||
c := composition(t)
|
||||
f := c.fixture(t)
|
||||
lister := bindRole(t, f, func(s *Store) (issueops.BlockedLister, error) { return s.BlockedLister() })
|
||||
conformance.RunBlockedLister(t, t.Context(), conformance.BlockedListerFixture{
|
||||
IssuePrefix: servedIssuePrefix + "-blk",
|
||||
BlockedLister: lister,
|
||||
CreateIssue: c.seedIssue,
|
||||
CreateWisp: c.seedIssue,
|
||||
AddDependency: c.seedDependency,
|
||||
})
|
||||
}
|
||||
|
|
@ -305,6 +305,8 @@ func serveConfig(t *testing.T, s storage.DoltStorage) httpapi.Config {
|
|||
fail("LeaseReclaimer")
|
||||
cfg.Heartbeater, err = s.Heartbeater()
|
||||
fail("Heartbeater")
|
||||
cfg.BlockedLister, err = s.BlockedLister()
|
||||
fail("BlockedLister")
|
||||
|
||||
// THE JOURNAL IS NOT AN ACCESSOR, alone among the roles above: it is reached
|
||||
// by TYPE ASSERTION, because it is not on storage.DoltStorage and a backend
|
||||
|
|
|
|||
|
|
@ -246,6 +246,9 @@ func serveRoles(store storage.DoltStorage) (httpapi.Config, error) {
|
|||
if cfg.Heartbeater, err = store.Heartbeater(); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
if cfg.BlockedLister, err = store.BlockedLister(); err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -232,11 +232,6 @@ func (unsupportedDoltStorage) GetAllEventsSince(_ context.Context, _ time.Time)
|
|||
return
|
||||
}
|
||||
|
||||
func (unsupportedDoltStorage) GetBlockedIssues(_ context.Context, _ types.WorkFilter) (_ []*types.BlockedIssue, err error) {
|
||||
err = errUnsupported("GetBlockedIssues")
|
||||
return
|
||||
}
|
||||
|
||||
func (unsupportedDoltStorage) GetBlockingInfoForIssues(_ context.Context, _ []string) (_ map[string][]string, _ map[string][]string, _ map[string]string, err error) {
|
||||
err = errUnsupported("GetBlockingInfoForIssues")
|
||||
return
|
||||
|
|
@ -722,4 +717,4 @@ func (unsupportedDoltStorage) VersionReconciler() (_ issueops.VersionReconciler,
|
|||
return
|
||||
}
|
||||
|
||||
// NOTE: partial shell (141 of 204 methods generated; 63 left to this package's hand-written set).
|
||||
// NOTE: partial shell (140 of 205 methods generated; 65 left to this package's hand-written set).
|
||||
|
|
|
|||
|
|
@ -111,6 +111,11 @@ var opCapability = map[string]string{
|
|||
// does not advertise the token, so Preflight refuses locally with a typed
|
||||
// capability error rather than dialing a route the older server lacks.
|
||||
OpHeartbeatIssue: "issues.heartbeat",
|
||||
// The blocked listing, dialed by httpBlockedLister. A server that
|
||||
// predates it does not advertise the token, so Preflight refuses locally
|
||||
// with a typed capability error naming blocked.list rather than dialing a
|
||||
// route the older server lacks.
|
||||
OpListBlockedIssues: "blocked.list",
|
||||
// The advance-a-molecule role (molecule.go) dials it when served and
|
||||
// refuses before dialing when not; it never composes a client-side copy.
|
||||
OpAdvanceMolecule: "issues.advanceMolecule",
|
||||
|
|
|
|||
|
|
@ -60,6 +60,7 @@ const (
|
|||
OpBatchGetIssues = "batchGetIssues"
|
||||
OpReclaimIssues = "reclaimIssues"
|
||||
OpHeartbeatIssue = "heartbeatIssue"
|
||||
OpListBlockedIssues = "listBlockedIssues"
|
||||
)
|
||||
|
||||
// The paths that carry no caller-supplied segment. A path with one is built by
|
||||
|
|
@ -69,6 +70,7 @@ const (
|
|||
PathContext = "/v0/beads/context"
|
||||
PathReady = "/v0/beads/ready"
|
||||
PathReadyCount = "/v0/beads/ready:count"
|
||||
PathBlocked = "/v0/beads/blocked"
|
||||
PathStats = "/v0/beads/stats"
|
||||
PathIssues = "/v0/beads/issues"
|
||||
PathIssuesQuery = "/v0/beads/issues:query"
|
||||
|
|
|
|||
|
|
@ -110,8 +110,8 @@ func TestAgainstAFirstSliceServerEveryPostBaselineOperationRefusesWithCaseTwoDat
|
|||
t.Fatalf("post-baseline ops on a first-slice token = %v, want exactly [claimIssue]", compat)
|
||||
}
|
||||
// The dimension is pinned so the matrix cannot shrink silently: the first
|
||||
// slice served six operations and the tip surface has forty-five, so
|
||||
// thirty-nine of them are things a first-slice server has never heard of. The
|
||||
// slice served six operations and the tip surface has forty-six, so
|
||||
// forty of them are things a first-slice server has never heard of. The
|
||||
// wire wave moved this from twenty-seven to thirty — claimNext, release and
|
||||
// count — wave 2 to thirty-two, adding the dependency-edge count and the
|
||||
// related read, the mini-sync to thirty-five: the comment write and the two
|
||||
|
|
@ -120,9 +120,10 @@ func TestAgainstAFirstSliceServerEveryPostBaselineOperationRefusesWithCaseTwoDat
|
|||
// an operation a first-slice server never served and this client does not
|
||||
// yet dial, which is exactly the shape the refusal matrix is about. The
|
||||
// molecule advance (S16) makes thirty-eight, and the lease refresh
|
||||
// (issues.heartbeat) thirty-nine.
|
||||
if len(refused) != 39 {
|
||||
t.Fatalf("the post-baseline set has %d operations a first-slice server never served, want 39", len(refused))
|
||||
// (issues.heartbeat) thirty-nine, and the blocked listing (blocked.list)
|
||||
// forty.
|
||||
if len(refused) != 40 {
|
||||
t.Fatalf("the post-baseline set has %d operations a first-slice server never served, want 40", len(refused))
|
||||
}
|
||||
|
||||
// The compat op forces the handshake yet preflights clean: issues.claim is on
|
||||
|
|
|
|||
|
|
@ -70,6 +70,7 @@ func TestOperationIdsMatchTheServerRouteTable(t *testing.T) {
|
|||
{OpBatchGetIssues, httpapi.OpBatchGetIssues},
|
||||
{OpReclaimIssues, httpapi.OpReclaimIssues},
|
||||
{OpHeartbeatIssue, httpapi.OpHeartbeatIssue},
|
||||
{OpListBlockedIssues, httpapi.OpListBlockedIssues},
|
||||
{OpAdvanceMolecule, httpapi.OpAdvanceMolecule},
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ go_library(
|
|||
"hook_batch_closer.go",
|
||||
"hook_batch_creator.go",
|
||||
"hook_batch_getter.go",
|
||||
"hook_blocked_lister.go",
|
||||
"hook_blockingannotator.go",
|
||||
"hook_bootstrapper.go",
|
||||
"hook_commenter.go",
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ go_library(
|
|||
"batch_closer.go",
|
||||
"batch_creator.go",
|
||||
"batchgetter.go",
|
||||
"blocked_lister.go",
|
||||
"blocked_recheck_raw.go",
|
||||
"blockingannotator.go",
|
||||
"bootstrap.go",
|
||||
|
|
@ -143,6 +144,7 @@ go_test(
|
|||
"batch_getter_contract_test.go",
|
||||
"blocked_consistency_test.go",
|
||||
"blocked_full_repair_test.go",
|
||||
"blocked_lister_contract_test.go",
|
||||
"blocked_merge_test.go",
|
||||
"blocked_recheck_phase_test.go",
|
||||
"blocked_recheck_publication_test.go",
|
||||
|
|
|
|||
38
internal/storage/dolt/blocked_lister.go
Normal file
38
internal/storage/dolt/blocked_lister.go
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
package dolt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
storeops "github.com/steveyegge/beads/internal/storage/issueops"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// BlockedLister returns the blocked-listing surface for this store.
|
||||
func (s *DoltStore) BlockedLister() (issueops.BlockedLister, error) {
|
||||
if s == nil {
|
||||
return nil, &storage.ErrUnsupported{Op: "BlockedLister", Backend: "nil"}
|
||||
}
|
||||
return &blockedLister{store: s}, nil
|
||||
}
|
||||
|
||||
// blockedLister answers a ListBlocked from one read transaction around the
|
||||
// shared body, storeops.ExecuteListBlockedInTx, the same body GetBlockedIssues
|
||||
// runs.
|
||||
type blockedLister struct{ store *DoltStore }
|
||||
|
||||
var _ issueops.BlockedLister = (*blockedLister)(nil)
|
||||
|
||||
func (l *blockedLister) ListBlocked(ctx context.Context, req issueops.BlockedRequest) (issueops.BlockedResult, error) {
|
||||
var result issueops.BlockedResult
|
||||
err := l.store.withReadTx(ctx, func(tx *sql.Tx) error {
|
||||
var err error
|
||||
result, err = storeops.ExecuteListBlockedInTx(ctx, tx, req)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return issueops.BlockedResult{}, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
40
internal/storage/dolt/blocked_lister_contract_test.go
Normal file
40
internal/storage/dolt/blocked_lister_contract_test.go
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
package dolt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/backend/conformance"
|
||||
)
|
||||
|
||||
// TestBlockedListerContract runs the BlockedLister contract against the
|
||||
// server-backed store.
|
||||
func TestBlockedListerContract(t *testing.T) {
|
||||
store, cleanup := setupTestStore(t)
|
||||
defer cleanup()
|
||||
ctx, cancel := testContext(t)
|
||||
defer cancel()
|
||||
lister, err := store.BlockedLister()
|
||||
if err != nil {
|
||||
t.Fatalf("BlockedLister(): %v", err)
|
||||
}
|
||||
kit := newDoltRoleFixtureKit(store, "blk")
|
||||
conformance.RunBlockedLister(t, ctx, conformance.BlockedListerFixture{
|
||||
IssuePrefix: kit.IssuePrefix,
|
||||
BlockedLister: lister,
|
||||
CreateIssue: kit.CreateIssue,
|
||||
CreateWisp: kit.CreateWisp,
|
||||
AddDependency: kit.AddDependency,
|
||||
MarkBlocked: func(ctx context.Context, id string) error {
|
||||
res, err := store.db.ExecContext(ctx, "UPDATE issues SET is_blocked = 1 WHERE id = ?", id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, err := res.RowsAffected(); err != nil || n != 1 {
|
||||
return fmt.Errorf("marked %d rows (err %v), want 1", n, err)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@ go_library(
|
|||
"batch_closer.go",
|
||||
"batch_creator.go",
|
||||
"batchgetter.go",
|
||||
"blocked_lister.go",
|
||||
"blockingannotator.go",
|
||||
"bootstrapper.go",
|
||||
"cache.go",
|
||||
|
|
@ -110,6 +111,7 @@ go_test(
|
|||
"batch_closer_contract_test.go",
|
||||
"batch_creator_contract_test.go",
|
||||
"batch_getter_contract_test.go",
|
||||
"blocked_lister_contract_test.go",
|
||||
"blocked_recheck_internal_test.go",
|
||||
"blocked_recompute_test.go",
|
||||
"blocking_annotator_batch_test.go",
|
||||
|
|
|
|||
40
internal/storage/embeddeddolt/blocked_lister.go
Normal file
40
internal/storage/embeddeddolt/blocked_lister.go
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
//go:build cgo
|
||||
|
||||
package embeddeddolt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
storeops "github.com/steveyegge/beads/internal/storage/issueops"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// BlockedLister returns the blocked-listing surface for this store.
|
||||
func (s *EmbeddedDoltStore) BlockedLister() (issueops.BlockedLister, error) {
|
||||
if s == nil {
|
||||
return nil, &storage.ErrUnsupported{Op: "BlockedLister", Backend: "nil"}
|
||||
}
|
||||
return &blockedLister{store: s}, nil
|
||||
}
|
||||
|
||||
// blockedLister answers a ListBlocked from one read-only connection around
|
||||
// the shared body, storeops.ExecuteListBlockedInTx, the same body
|
||||
// GetBlockedIssues runs.
|
||||
type blockedLister struct{ store *EmbeddedDoltStore }
|
||||
|
||||
var _ issueops.BlockedLister = (*blockedLister)(nil)
|
||||
|
||||
func (l *blockedLister) ListBlocked(ctx context.Context, req issueops.BlockedRequest) (issueops.BlockedResult, error) {
|
||||
var result issueops.BlockedResult
|
||||
err := l.store.withConn(ctx, false, func(tx *sql.Tx) error {
|
||||
var err error
|
||||
result, err = storeops.ExecuteListBlockedInTx(ctx, tx, req)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return issueops.BlockedResult{}, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
//go:build cgo
|
||||
|
||||
package embeddeddolt_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/backend/conformance"
|
||||
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
|
||||
)
|
||||
|
||||
// TestBlockedListerContract runs the BlockedLister contract against the
|
||||
// embedded store.
|
||||
func TestBlockedListerContract(t *testing.T) {
|
||||
skipUnlessEmbeddedDolt(t)
|
||||
te := newTestEnv(t, "blk")
|
||||
lister, err := te.store.BlockedLister()
|
||||
if err != nil {
|
||||
t.Fatalf("BlockedLister(): %v", err)
|
||||
}
|
||||
kit := newEmbeddedRoleFixtureKit(te, "blk")
|
||||
conformance.RunBlockedLister(t, t.Context(), conformance.BlockedListerFixture{
|
||||
IssuePrefix: kit.IssuePrefix,
|
||||
BlockedLister: lister,
|
||||
CreateIssue: kit.CreateIssue,
|
||||
CreateWisp: kit.CreateWisp,
|
||||
AddDependency: kit.AddDependency,
|
||||
MarkBlocked: func(ctx context.Context, id string) error {
|
||||
db, cleanup, err := embeddeddolt.OpenSQL(ctx, te.dataDir, te.database, "main")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = cleanup() }()
|
||||
res, err := db.ExecContext(ctx, "UPDATE issues SET is_blocked = 1 WHERE id = ?", id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, err := res.RowsAffected(); err != nil || n != 1 {
|
||||
return fmt.Errorf("marked %d rows (err %v), want 1", n, err)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ go_library(
|
|||
name = "externaldeps",
|
||||
srcs = [
|
||||
"batch_closer.go",
|
||||
"blocked_lister.go",
|
||||
"decorator.go",
|
||||
"remote_roles.go",
|
||||
"resolver.go",
|
||||
|
|
@ -30,6 +31,7 @@ go_test(
|
|||
name = "externaldeps_test",
|
||||
srcs = [
|
||||
"advertise_test.go",
|
||||
"blocked_lister_test.go",
|
||||
"blocking_annotator_batch_test.go",
|
||||
"decorator_test.go",
|
||||
"ready_wake_test.go",
|
||||
|
|
|
|||
114
internal/storage/externaldeps/blocked_lister.go
Normal file
114
internal/storage/externaldeps/blocked_lister.go
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
package externaldeps
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
storageissueops "github.com/steveyegge/beads/internal/storage/issueops"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// BlockedLister lists the blocked issues through GetBlockedIssues above, so
|
||||
// the role names unsatisfied external blockers exactly as the legacy read
|
||||
// does, and `bd blocked` answers the same on either. It must be overridden
|
||||
// here: the embedded passthrough would hand back the inner store's lister,
|
||||
// which knows nothing of external refs.
|
||||
//
|
||||
// The inner layers get their turn back the way ReadyCounter gives it: the
|
||||
// finished lister is wrapped by a decorator beneath that offers
|
||||
// WrapBlockedLister (telemetry), asserted rather than imported.
|
||||
//
|
||||
// A remote store answers with its own lister (the server's blocked
|
||||
// operation) whenever its server applies the policy itself, since that
|
||||
// server's own decorator stack has already named the external blockers;
|
||||
// against any other server the server's listing is decorated here, through
|
||||
// reads a served store answers (EdgeReader, BatchGetter). remoteBlockedLister
|
||||
// decides per call, since the handshake is read lazily, and a failed probe
|
||||
// fails the call rather than skipping the policy. Unlike ReadyCounter's, the
|
||||
// remote lister keeps no local leg to fall back on, so no local lister is
|
||||
// built for it: the inner store's lister already carries the inner layers.
|
||||
// Nor is remoteBlockedLister wrapped again: with telemetry on, the inner
|
||||
// lister already carries its span around the server's listing, and wrapping
|
||||
// would nest a second span of the same name. The policy probe, and the
|
||||
// decoration against a server that leaves the policy to its clients, run
|
||||
// outside that span.
|
||||
func (s *Store) BlockedLister() (issueops.BlockedLister, error) {
|
||||
if s.rolesAreRemote() {
|
||||
inner, err := s.inner.BlockedLister()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &remoteBlockedLister{inner: inner, policy: s}, nil
|
||||
}
|
||||
lister, err := storageissueops.NewBlockedListerOver(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if wrapper, ok := s.inner.(blockedListerWrapper); ok {
|
||||
lister = wrapper.WrapBlockedLister(lister)
|
||||
}
|
||||
return lister, nil
|
||||
}
|
||||
|
||||
// blockedListerWrapper is how a decorator beneath this one adds its layer to
|
||||
// a blocked lister it did not construct.
|
||||
type blockedListerWrapper interface {
|
||||
WrapBlockedLister(issueops.BlockedLister) issueops.BlockedLister
|
||||
}
|
||||
|
||||
type remoteBlockedLister struct {
|
||||
inner issueops.BlockedLister
|
||||
policy *Store
|
||||
}
|
||||
|
||||
// ListBlocked is the server's listing when the server applies the policy.
|
||||
// Against any other server it is that listing with the external blockers
|
||||
// added here, the decoration GetBlockedIssues makes over a local store.
|
||||
func (l *remoteBlockedLister) ListBlocked(ctx context.Context, req issueops.BlockedRequest) (issueops.BlockedResult, error) {
|
||||
enforced, err := l.policy.serverEnforcesPolicy(ctx)
|
||||
if err != nil {
|
||||
return issueops.BlockedResult{}, err
|
||||
}
|
||||
result, err := l.inner.ListBlocked(ctx, req)
|
||||
if err != nil || enforced {
|
||||
return result, err
|
||||
}
|
||||
items, err := l.policy.decorateBlocked(ctx, storageissueops.BlockedFilter(req), result.Items,
|
||||
l.policy.remoteEdges, l.policy.remoteIssuesByIDs)
|
||||
if err != nil {
|
||||
return issueops.BlockedResult{}, err
|
||||
}
|
||||
return storageissueops.BlockedResultOf(items), nil
|
||||
}
|
||||
|
||||
// remoteIssuesByIDs reads rows by id through the inner BatchGetter, which a
|
||||
// served store answers.
|
||||
func (s *Store) remoteIssuesByIDs(ctx context.Context, ids []string) ([]*types.Issue, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
getter, err := s.inner.BatchGetter()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return getManyChunked(ctx, getter, ids)
|
||||
}
|
||||
|
||||
// getManyChunked reads rows by id through getter, in requests of at most
|
||||
// issueops.MaxGetManyIDs ids, both planes, labels hydrated (GetMany's one
|
||||
// hydration, the label filter's input). A missing id is simply absent, as
|
||||
// GetIssuesByIDs leaves it.
|
||||
func getManyChunked(ctx context.Context, getter issueops.BatchGetter, ids []string) ([]*types.Issue, error) {
|
||||
var out []*types.Issue
|
||||
for start := 0; start < len(ids); start += issueops.MaxGetManyIDs {
|
||||
end := min(start+issueops.MaxGetManyIDs, len(ids))
|
||||
res, err := getter.GetMany(ctx, issueops.GetManyRequest{IDs: ids[start:end]})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, res.Issues...)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
var _ issueops.BlockedLister = (*remoteBlockedLister)(nil)
|
||||
176
internal/storage/externaldeps/blocked_lister_test.go
Normal file
176
internal/storage/externaldeps/blocked_lister_test.go
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
package externaldeps
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
storageissueops "github.com/steveyegge/beads/internal/storage/issueops"
|
||||
"github.com/steveyegge/beads/internal/storage/uow"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// TestWrapUOWProviderBlockedListerNamesExternalBlockers pins the blocked
|
||||
// listing on the composition every `bd serve` answers from: the unit-of-work
|
||||
// provider wrapped by this package (cmd/bd's wireExternalDependencyUOWProvider)
|
||||
// handing out BlockedLister through its own accessor. The server advertises
|
||||
// policy.external_dependencies for this composition, so its listing is the one
|
||||
// a client stands down to, and it must already carry the external refs:
|
||||
//
|
||||
// - a row blocked ONLY by an unsatisfied external ref is listed, with the
|
||||
// ref as its blocker (the undecorated listing never names it, because the
|
||||
// stored blocked flag knows nothing of other projects);
|
||||
// - a row with a local blocker AND an external ref names both.
|
||||
//
|
||||
// A lister built over the inner provider rather than this one would lose
|
||||
// both, and gc reads the missing row as unblocked.
|
||||
func TestWrapUOWProviderBlockedListerNamesExternalBlockers(t *testing.T) {
|
||||
local, mixed, extOnly := issue("be-local"), issue("be-mixed"), issue("be-ext")
|
||||
mixed.Priority, extOnly.Priority = 1, 2
|
||||
inner := &fakeUOW{
|
||||
issues: &fakeIssueUseCase{
|
||||
ready: []*types.Issue{local, mixed, extOnly},
|
||||
blocked: []*types.BlockedIssue{
|
||||
{Issue: *mixed, BlockedByCount: 1, BlockedBy: []string{local.ID}},
|
||||
},
|
||||
},
|
||||
deps: &fakeDependencyUseCase{
|
||||
external: map[string][]*types.Dependency{
|
||||
mixed.ID: {externalDep(mixed.ID, "external:remote:billing", types.DepBlocks)},
|
||||
extOnly.ID: {externalDep(extOnly.ID, "external:remote:payments", types.DepBlocks)},
|
||||
},
|
||||
},
|
||||
}
|
||||
provider := WrapUOWProvider(&fakeUOWProvider{uw: inner}, func(ProjectName) (string, bool) {
|
||||
return "", false
|
||||
}, nil)
|
||||
source, ok := provider.(uow.BlockedListerSource)
|
||||
if !ok {
|
||||
t.Fatalf("wrapped provider %T does not offer BlockedLister", provider)
|
||||
}
|
||||
lister, err := source.BlockedLister()
|
||||
if err != nil {
|
||||
t.Fatalf("BlockedLister: %v", err)
|
||||
}
|
||||
result, err := lister.ListBlocked(t.Context(), publicops.BlockedRequest{})
|
||||
if err != nil {
|
||||
t.Fatalf("ListBlocked: %v", err)
|
||||
}
|
||||
got := map[string][]string{}
|
||||
var order []string
|
||||
for _, item := range result.Items {
|
||||
blockers := slices.Clone(item.BlockedBy)
|
||||
slices.Sort(blockers)
|
||||
got[item.ID] = blockers
|
||||
order = append(order, item.ID)
|
||||
if item.BlockedByCount != len(item.BlockedBy) {
|
||||
t.Errorf("%s: BlockedByCount = %d, len(BlockedBy) = %d", item.ID, item.BlockedByCount, len(item.BlockedBy))
|
||||
}
|
||||
}
|
||||
want := map[string][]string{
|
||||
mixed.ID: {local.ID, "external:remote:billing"},
|
||||
extOnly.ID: {"external:remote:payments"},
|
||||
}
|
||||
slices.Sort(want[mixed.ID])
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("listing = %v, want %v", got, want)
|
||||
}
|
||||
if !slices.Equal(order, []string{mixed.ID, extOnly.ID}) {
|
||||
t.Errorf("order = %v, want priority order [%s %s]", order, mixed.ID, extOnly.ID)
|
||||
}
|
||||
}
|
||||
|
||||
// externalOnlyLabelCases are label filters over two rows blocked ONLY by an
|
||||
// unsatisfied external ref (externalOnlyLabelRows): be-tagged carries lane:a
|
||||
// and team:x, be-bare carries no label. The undecorated listing, whose SQL
|
||||
// applies the label clauses, never sees either row; the decoration adds them
|
||||
// after that query ran, so each want is what those clauses answer for a row
|
||||
// the query lists itself.
|
||||
var externalOnlyLabelCases = []struct {
|
||||
name string
|
||||
req publicops.BlockedRequest
|
||||
want []string
|
||||
}{
|
||||
{"no filter", publicops.BlockedRequest{}, []string{"be-tagged", "be-bare"}},
|
||||
{"label", publicops.BlockedRequest{Labels: []string{"lane:a"}}, []string{"be-tagged"}},
|
||||
{"labels are all required", publicops.BlockedRequest{Labels: []string{"lane:a", "team:y"}}, nil},
|
||||
{"label matches exactly", publicops.BlockedRequest{Labels: []string{"Lane:A"}}, nil},
|
||||
{"label_any", publicops.BlockedRequest{LabelsAny: []string{"lane:b", "team:x"}}, []string{"be-tagged"}},
|
||||
{"label_any matching none", publicops.BlockedRequest{LabelsAny: []string{"lane:b"}}, nil},
|
||||
{"exclude_label", publicops.BlockedRequest{ExcludeLabels: []string{"lane:a"}}, []string{"be-bare"}},
|
||||
{"exclude_label matching none", publicops.BlockedRequest{ExcludeLabels: []string{"lane:b"}}, []string{"be-tagged", "be-bare"}},
|
||||
{"label and exclude_label", publicops.BlockedRequest{Labels: []string{"lane:a"}, ExcludeLabels: []string{"team:x"}}, nil},
|
||||
}
|
||||
|
||||
func externalOnlyLabelRows() ([]*types.Issue, map[string][]*types.Dependency) {
|
||||
tagged, bare := issue("be-tagged"), issue("be-bare")
|
||||
tagged.Priority, bare.Priority = 1, 2
|
||||
tagged.Labels = []string{"lane:a", "team:x"}
|
||||
return []*types.Issue{tagged, bare}, map[string][]*types.Dependency{
|
||||
tagged.ID: {externalDep(tagged.ID, "external:remote:payments", types.DepBlocks)},
|
||||
bare.ID: {externalDep(bare.ID, "external:remote:payments", types.DepBlocks)},
|
||||
}
|
||||
}
|
||||
|
||||
// TestBlockedListingFiltersExternalOnlyRowsByLabel pins the label filters on
|
||||
// the rows the decoration adds, on both of this package's compositions, each
|
||||
// read through the role and through the legacy GetBlockedIssues door: the
|
||||
// store decorator (the direct and embedded routes, a store-shaped bd serve,
|
||||
// and the http client's own decoration, which shares decorateBlocked) and the
|
||||
// unit-of-work decorator (the proxied route and a provider-shaped bd serve,
|
||||
// whose plain by-id reads hydrate no labels at all).
|
||||
func TestBlockedListingFiltersExternalOnlyRowsByLabel(t *testing.T) {
|
||||
t.Run("store", func(t *testing.T) {
|
||||
rows, deps := externalOnlyLabelRows()
|
||||
store := testStore(&fakeStore{ready: rows, deps: deps}, &fakeStore{}, false)
|
||||
lister, err := store.BlockedLister()
|
||||
if err != nil {
|
||||
t.Fatalf("BlockedLister: %v", err)
|
||||
}
|
||||
runExternalOnlyLabelCases(t, lister, store.GetBlockedIssues)
|
||||
})
|
||||
t.Run("unit of work", func(t *testing.T) {
|
||||
rows, deps := externalOnlyLabelRows()
|
||||
provider := WrapUOWProvider(&fakeUOWProvider{uw: &fakeUOW{
|
||||
issues: &fakeIssueUseCase{ready: rows},
|
||||
deps: &fakeDependencyUseCase{external: deps},
|
||||
}}, func(ProjectName) (string, bool) { return "", false }, nil)
|
||||
source, ok := provider.(uow.BlockedListerSource)
|
||||
if !ok {
|
||||
t.Fatalf("wrapped provider %T does not offer BlockedLister", provider)
|
||||
}
|
||||
lister, err := source.BlockedLister()
|
||||
if err != nil {
|
||||
t.Fatalf("BlockedLister: %v", err)
|
||||
}
|
||||
uw, err := provider.NewUOW(t.Context())
|
||||
if err != nil {
|
||||
t.Fatalf("NewUOW: %v", err)
|
||||
}
|
||||
runExternalOnlyLabelCases(t, lister, uw.IssueUseCase().GetBlockedIssues)
|
||||
})
|
||||
}
|
||||
|
||||
func runExternalOnlyLabelCases(t *testing.T, lister publicops.BlockedLister, legacy func(context.Context, types.WorkFilter) ([]*types.BlockedIssue, error)) {
|
||||
t.Helper()
|
||||
for _, tc := range externalOnlyLabelCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
result, err := lister.ListBlocked(t.Context(), tc.req)
|
||||
if err != nil {
|
||||
t.Fatalf("ListBlocked: %v", err)
|
||||
}
|
||||
if ids := blockedIssueIDs(result.Items); !slices.Equal(ids, tc.want) {
|
||||
t.Errorf("ListBlocked = %v, want %v", ids, tc.want)
|
||||
}
|
||||
items, err := legacy(t.Context(), storageissueops.BlockedFilter(tc.req))
|
||||
if err != nil {
|
||||
t.Fatalf("GetBlockedIssues: %v", err)
|
||||
}
|
||||
if ids := blockedIssueIDs(items); !slices.Equal(ids, tc.want) {
|
||||
t.Errorf("GetBlockedIssues = %v, want %v", ids, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -576,6 +576,33 @@ func (s *Store) GetBlockedIssues(ctx context.Context, filter types.WorkFilter) (
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A served store refuses the two raw reads the decoration makes for the
|
||||
// extra sources; over one they go through the roles it serves, as the
|
||||
// remote blocked lister's do (blocked_lister.go). Against a server that
|
||||
// applies the policy itself the decoration adds nothing (loadBlockingState
|
||||
// stands down) and neither read is made.
|
||||
dependencyRecords, issuesByIDs := s.inner.GetDependencyRecordsForIssues, s.inner.GetIssuesByIDs
|
||||
if s.rolesAreRemote() {
|
||||
dependencyRecords, issuesByIDs = s.remoteEdges, s.remoteIssuesByIDs
|
||||
}
|
||||
return s.decorateBlocked(ctx, filter, base, dependencyRecords, issuesByIDs)
|
||||
}
|
||||
|
||||
// decorateBlocked is GetBlockedIssues' decoration of an undecorated blocked
|
||||
// listing (base): unsatisfied external refs are added to each row's blockers,
|
||||
// and the sources blocked only by such refs are listed too, narrowed by the
|
||||
// same parent and label filters the base listing was. The two reads it makes
|
||||
// for those extra sources (their parent edges, when the filter names a
|
||||
// parent, and the rows themselves, labels hydrated as GetIssuesByIDs and
|
||||
// GetMany both hydrate them) are passed in, so the remote blocked lister can
|
||||
// make them through roles a served store answers.
|
||||
func (s *Store) decorateBlocked(
|
||||
ctx context.Context,
|
||||
filter types.WorkFilter,
|
||||
base []*types.BlockedIssue,
|
||||
dependencyRecords func(context.Context, []string) (map[string][]*types.Dependency, error),
|
||||
issuesByIDs func(context.Context, []string) ([]*types.Issue, error),
|
||||
) ([]*types.BlockedIssue, error) {
|
||||
state, err := s.loadBlockingState(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
@ -605,7 +632,7 @@ func (s *Store) GetBlockedIssues(ctx context.Context, filter types.WorkFilter) (
|
|||
}
|
||||
parentDeps := make(map[string][]*types.Dependency)
|
||||
if filter.ParentID != nil && len(missingIDs) > 0 {
|
||||
parentDeps, err = s.inner.GetDependencyRecordsForIssues(ctx, missingIDs)
|
||||
parentDeps, err = dependencyRecords(ctx, missingIDs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("external dependencies: load blocked parent edges: %w", err)
|
||||
}
|
||||
|
|
@ -616,14 +643,20 @@ func (s *Store) GetBlockedIssues(ctx context.Context, filter types.WorkFilter) (
|
|||
filteredMissingIDs = append(filteredMissingIDs, issueID)
|
||||
}
|
||||
}
|
||||
issues, err := s.inner.GetIssuesByIDs(ctx, filteredMissingIDs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("external dependencies: load blocked sources: %w", err)
|
||||
var issues []*types.Issue
|
||||
if len(filteredMissingIDs) > 0 {
|
||||
issues, err = issuesByIDs(ctx, filteredMissingIDs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("external dependencies: load blocked sources: %w", err)
|
||||
}
|
||||
}
|
||||
for _, issue := range issues {
|
||||
if issue == nil || issue.Status == types.StatusClosed || issue.Status == types.StatusPinned {
|
||||
continue
|
||||
}
|
||||
if !matchesLabelFilter(issue.Labels, filter) {
|
||||
continue
|
||||
}
|
||||
refs := slices.Clone(state.refsByIssue[issue.ID])
|
||||
blocked := &types.BlockedIssue{
|
||||
Issue: *issue,
|
||||
|
|
@ -687,6 +720,32 @@ func matchesParentFilter(issueID string, parentID *string, allDeps map[string][]
|
|||
return false
|
||||
}
|
||||
|
||||
// matchesLabelFilter is the label half of the blocked body's filter
|
||||
// (sqlbuild.LabelSetClauses in issueops.GetBlockedIssuesInTx), for a row the
|
||||
// decoration adds after that query ran: every Labels entry present, at least
|
||||
// one LabelsAny entry present when any is named, and no ExcludeLabels entry
|
||||
// present. It compares with Go string equality, which is the SQL comparison
|
||||
// under the collation every beads table is created with (utf8mb4_0900_bin;
|
||||
// see issueops' createBatchCache).
|
||||
func matchesLabelFilter(labels []string, filter types.WorkFilter) bool {
|
||||
for _, label := range filter.Labels {
|
||||
if !slices.Contains(labels, label) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if len(filter.LabelsAny) > 0 && !slices.ContainsFunc(filter.LabelsAny, func(label string) bool {
|
||||
return slices.Contains(labels, label)
|
||||
}) {
|
||||
return false
|
||||
}
|
||||
for _, label := range filter.ExcludeLabels {
|
||||
if slices.Contains(labels, label) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// IsBlocked includes explicit unsatisfied external blockers in the close guard.
|
||||
// A store that serves its roles refuses the reads this makes, so over one the
|
||||
// per-issue roles in remote_roles.go answer instead.
|
||||
|
|
|
|||
|
|
@ -148,7 +148,14 @@ func (p *uowProvider) LeaseReclaimer() (publicops.LeaseReclaimer, error) {
|
|||
// Heartbeater passes through: the external-dependency policy governs what a
|
||||
// write may point at, and a heartbeat on an existing claim points at nothing.
|
||||
func (p *uowProvider) Heartbeater() (publicops.Heartbeater, error) { return uow.NewHeartbeater(p) }
|
||||
func (p *uowProvider) Memories() (memoryops.Memories, error) { return uow.NewMemories(p) }
|
||||
|
||||
// BlockedLister is built over THIS provider, so its unit of work's
|
||||
// GetBlockedIssues is the decorated one above: unsatisfied external blockers
|
||||
// are named, exactly as the store decorator names them.
|
||||
func (p *uowProvider) BlockedLister() (publicops.BlockedLister, error) {
|
||||
return uow.NewBlockedLister(p)
|
||||
}
|
||||
func (p *uowProvider) Memories() (memoryops.Memories, error) { return uow.NewMemories(p) }
|
||||
func (p *uowProvider) EventsJournalCursor() (storage.EventsJournalCursor, error) {
|
||||
return uow.NewEventsJournalCursor(p)
|
||||
}
|
||||
|
|
@ -227,6 +234,7 @@ var (
|
|||
_ uow.ReleaserSource = (*uowProvider)(nil)
|
||||
_ uow.LeaseReclaimerSource = (*uowProvider)(nil)
|
||||
_ uow.HeartbeaterSource = (*uowProvider)(nil)
|
||||
_ uow.BlockedListerSource = (*uowProvider)(nil)
|
||||
_ uow.MemoriesSource = (*uowProvider)(nil)
|
||||
_ uow.EventsJournalCursorSource = (*uowProvider)(nil)
|
||||
)
|
||||
|
|
@ -350,20 +358,18 @@ func (u *issueUseCase) GetBlockedIssues(ctx context.Context, filter types.WorkFi
|
|||
parentDeps[id] = append(parentDeps[id], deps...)
|
||||
}
|
||||
}
|
||||
issues, err := u.IssueUseCase.GetIssuesByIDs(ctx, missing)
|
||||
// GetMany reads both planes with labels hydrated, as the store decorator's
|
||||
// reads do; GetIssuesByIDs here would leave Labels empty, so the label
|
||||
// filter below could not judge these rows and they would print unlabelled.
|
||||
issues, err := getManyChunked(ctx, u.IssueUseCase, missing)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("external dependencies: load blocked sources: %w", err)
|
||||
}
|
||||
wisps, err := u.IssueUseCase.GetWispsByIDs(ctx, missing)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("external dependencies: load blocked wisp sources: %w", err)
|
||||
}
|
||||
issues = append(issues, wisps...)
|
||||
for _, issue := range issues {
|
||||
if issue == nil || issue.Status == types.StatusClosed || issue.Status == types.StatusPinned {
|
||||
continue
|
||||
}
|
||||
if !matchesParentFilter(issue.ID, filter.ParentID, parentDeps) {
|
||||
if !matchesParentFilter(issue.ID, filter.ParentID, parentDeps) || !matchesLabelFilter(issue.Labels, filter) {
|
||||
continue
|
||||
}
|
||||
refs := slices.Clone(state.refsByIssue[issue.ID])
|
||||
|
|
|
|||
|
|
@ -54,18 +54,6 @@ func (u *fakeIssueUseCase) GetIssue(_ context.Context, id string) (*types.Issue,
|
|||
return nil, nil
|
||||
}
|
||||
|
||||
func (u *fakeIssueUseCase) GetIssuesByIDs(ctx context.Context, ids []string) ([]*types.Issue, error) {
|
||||
result := make([]*types.Issue, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if issue, err := u.GetIssue(ctx, id); err != nil {
|
||||
return nil, err
|
||||
} else if issue != nil {
|
||||
result = append(result, issue)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (u *fakeIssueUseCase) GetWisp(_ context.Context, id string) (*types.Issue, error) {
|
||||
for _, issue := range u.wisps {
|
||||
if issue.ID == id {
|
||||
|
|
@ -75,16 +63,23 @@ func (u *fakeIssueUseCase) GetWisp(_ context.Context, id string) (*types.Issue,
|
|||
return nil, nil
|
||||
}
|
||||
|
||||
func (u *fakeIssueUseCase) GetWispsByIDs(ctx context.Context, ids []string) ([]*types.Issue, error) {
|
||||
result := make([]*types.Issue, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
issue, err := u.GetWisp(ctx, id)
|
||||
// GetMany answers both planes, as ExecuteGetMany does, each row with the
|
||||
// labels it was seeded with (GetMany's one hydration).
|
||||
func (u *fakeIssueUseCase) GetMany(ctx context.Context, request publicops.GetManyRequest) (publicops.GetManyResult, error) {
|
||||
result := publicops.GetManyResult{Issues: []*publicops.Issue{}, Missing: []string{}}
|
||||
for _, id := range request.IDs {
|
||||
issue, err := u.GetIssue(ctx, id)
|
||||
if err == nil && issue == nil {
|
||||
issue, err = u.GetWisp(ctx, id)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return publicops.GetManyResult{}, err
|
||||
}
|
||||
if issue != nil {
|
||||
result = append(result, issue)
|
||||
if issue == nil {
|
||||
result.Missing = append(result.Missing, id)
|
||||
continue
|
||||
}
|
||||
result.Issues = append(result.Issues, issue)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
|
|
|||
14
internal/storage/hook_blocked_lister.go
Normal file
14
internal/storage/hook_blocked_lister.go
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
package storage
|
||||
|
||||
import (
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// BlockedLister returns the inner store's blocked-listing surface.
|
||||
//
|
||||
// It recurses, like every other accessor on this decorator, and does not wrap
|
||||
// the result: listing the blocked issues fires no completion hook, because
|
||||
// nothing completed (hook_ready_counter.go makes the same statement).
|
||||
func (h *HookFiringStore) BlockedLister() (issueops.BlockedLister, error) {
|
||||
return h.inner.BlockedLister()
|
||||
}
|
||||
|
|
@ -13,6 +13,7 @@ go_library(
|
|||
"blocked_merge.go",
|
||||
"blocked_recheck.go",
|
||||
"blocked_recheck_report.go",
|
||||
"blocked_role.go",
|
||||
"blocked_state.go",
|
||||
"blocking_annotation.go",
|
||||
"bootstrap.go",
|
||||
|
|
@ -116,6 +117,7 @@ go_library(
|
|||
"//internal/storage/rowid",
|
||||
"//internal/storage/sqlbuild",
|
||||
"//internal/types",
|
||||
"//internal/utils",
|
||||
"//internal/workapi",
|
||||
"//issueops",
|
||||
"@com_github_dolthub_go_mysql_server//sql",
|
||||
|
|
|
|||
114
internal/storage/issueops/blocked_role.go
Normal file
114
internal/storage/issueops/blocked_role.go
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
package issueops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/utils"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// BlockedFilter is the WorkFilter a BlockedRequest compiles to: the filter
|
||||
// `bd blocked` has always handed GetBlockedIssues, built from the same four
|
||||
// flags. Labels are normalized as every other label filter normalizes them
|
||||
// (trimmed, blanks and repeats dropped): these clauses match a label EXACTLY,
|
||||
// so an untrimmed `--label 'a, b'` value would otherwise match nothing.
|
||||
//
|
||||
// It never writes through the request's slices (utils.NormalizeLabels
|
||||
// returns a new one), and it sets no page: the listing has none.
|
||||
func BlockedFilter(req publicops.BlockedRequest) types.WorkFilter {
|
||||
var filter types.WorkFilter
|
||||
if req.ParentID != "" {
|
||||
parentID := req.ParentID
|
||||
filter.ParentID = &parentID
|
||||
}
|
||||
filter.Labels = utils.NormalizeLabels(req.Labels)
|
||||
filter.LabelsAny = utils.NormalizeLabels(req.LabelsAny)
|
||||
filter.ExcludeLabels = utils.NormalizeLabels(req.ExcludeLabels)
|
||||
return filter
|
||||
}
|
||||
|
||||
// BlockedResultOf finishes a blocked listing for the role: never nil, and in
|
||||
// the role's total order (priority ascending, created_at descending, id). A
|
||||
// row's blocker slice is never nil either, so it encodes as [] like the
|
||||
// count beside it says.
|
||||
//
|
||||
// The order is restated rather than trusted because the store body breaks no
|
||||
// tie between two rows of equal priority created in the same instant (it
|
||||
// sorts rows assembled from a map); the id makes the listing one answer on
|
||||
// every leg. The external-dependency decorator already finishes with the
|
||||
// same three keys, so this is a no-op over it.
|
||||
func BlockedResultOf(items []*types.BlockedIssue) publicops.BlockedResult {
|
||||
out := make([]*types.BlockedIssue, 0, len(items))
|
||||
for _, item := range items {
|
||||
if item == nil {
|
||||
continue
|
||||
}
|
||||
if item.BlockedBy == nil {
|
||||
clone := *item
|
||||
clone.BlockedBy = []string{}
|
||||
item = &clone
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
slices.SortStableFunc(out, func(a, b *types.BlockedIssue) int {
|
||||
if a.Priority != b.Priority {
|
||||
return a.Priority - b.Priority
|
||||
}
|
||||
if !a.CreatedAt.Equal(b.CreatedAt) {
|
||||
if a.CreatedAt.After(b.CreatedAt) {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
switch {
|
||||
case a.ID < b.ID:
|
||||
return -1
|
||||
case a.ID > b.ID:
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
return publicops.BlockedResult{Items: out}
|
||||
}
|
||||
|
||||
// ExecuteListBlockedInTx is the store-backed body behind
|
||||
// issueops.BlockedLister: GetBlockedIssuesInTx over the request's filter,
|
||||
// finished by BlockedResultOf, inside the caller's read transaction.
|
||||
func ExecuteListBlockedInTx(ctx context.Context, tx DBTX, req publicops.BlockedRequest) (publicops.BlockedResult, error) {
|
||||
items, err := GetBlockedIssuesInTx(ctx, tx, BlockedFilter(req))
|
||||
if err != nil {
|
||||
return publicops.BlockedResult{}, err
|
||||
}
|
||||
return BlockedResultOf(items), nil
|
||||
}
|
||||
|
||||
// BlockedIssuesReader is the legacy blocked read a BlockedLister can be built
|
||||
// over: storage.DoltStorage's GetBlockedIssues, and the external-dependency
|
||||
// decorator's override of it.
|
||||
type BlockedIssuesReader interface {
|
||||
GetBlockedIssues(ctx context.Context, filter types.WorkFilter) ([]*types.BlockedIssue, error)
|
||||
}
|
||||
|
||||
// NewBlockedListerOver returns the BlockedLister that answers through
|
||||
// reader's GetBlockedIssues. It is how a decorator that overrides that read
|
||||
// (externaldeps.Store) hands out the role with its own decoration, so the
|
||||
// role and the legacy read cannot answer differently.
|
||||
func NewBlockedListerOver(reader BlockedIssuesReader) (publicops.BlockedLister, error) {
|
||||
if reader == nil {
|
||||
return nil, fmt.Errorf("new blocked lister: reader must not be nil")
|
||||
}
|
||||
return blockedListerOver{reader: reader}, nil
|
||||
}
|
||||
|
||||
type blockedListerOver struct{ reader BlockedIssuesReader }
|
||||
|
||||
func (l blockedListerOver) ListBlocked(ctx context.Context, req publicops.BlockedRequest) (publicops.BlockedResult, error) {
|
||||
items, err := l.reader.GetBlockedIssues(ctx, BlockedFilter(req))
|
||||
if err != nil {
|
||||
return publicops.BlockedResult{}, err
|
||||
}
|
||||
return BlockedResultOf(items), nil
|
||||
}
|
||||
|
|
@ -68,7 +68,7 @@ func roleAccessorNamesOf(surface reflect.Type) (names, unclassified []string) {
|
|||
}
|
||||
|
||||
// TestEveryStoreRoleAccessorIsClassified fails when DoltStorage hands out an
|
||||
// interface the census cannot place. Every one of the thirty today is a
|
||||
// interface the census cannot place. Every one of the thirty-one today is a
|
||||
// facade role, so this costs nothing and closes the path where a role surface
|
||||
// grows a package and the census quietly stops covering it. (roleAccessorNames
|
||||
// is derived, so the count is prose and only this sentence goes stale — but it
|
||||
|
|
@ -151,7 +151,7 @@ func assertRoleAccessorsAreDeclared(t *testing.T, decorator reflect.Type) {
|
|||
}
|
||||
|
||||
// roleAccessorStore is a DoltStorage whose only real methods are the
|
||||
// thirty role accessors, each answering with a distinguishable sentinel
|
||||
// thirty-one role accessors, each answering with a distinguishable sentinel
|
||||
// so a test can tell a decorated surface from a passed-through one.
|
||||
type roleAccessorStore struct {
|
||||
DoltStorage
|
||||
|
|
@ -185,6 +185,7 @@ type roleAccessorStore struct {
|
|||
releaser issueops.Releaser
|
||||
leaseReclaimer issueops.LeaseReclaimer
|
||||
heartbeater issueops.Heartbeater
|
||||
blockedLister issueops.BlockedLister
|
||||
err error
|
||||
}
|
||||
|
||||
|
|
@ -220,6 +221,7 @@ func newRoleAccessorStore() *roleAccessorStore {
|
|||
releaser: sentinel,
|
||||
leaseReclaimer: sentinel,
|
||||
heartbeater: sentinel,
|
||||
blockedLister: sentinel,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -296,8 +298,11 @@ func (s *roleAccessorStore) LeaseReclaimer() (issueops.LeaseReclaimer, error) {
|
|||
func (s *roleAccessorStore) Heartbeater() (issueops.Heartbeater, error) {
|
||||
return s.heartbeater, s.err
|
||||
}
|
||||
func (s *roleAccessorStore) BlockedLister() (issueops.BlockedLister, error) {
|
||||
return s.blockedLister, s.err
|
||||
}
|
||||
|
||||
// roleAccessorSentinel implements twenty-nine of the thirty roles at
|
||||
// roleAccessorSentinel implements thirty of the thirty-one roles at
|
||||
// once — every one but memoryops.Memories, whose List collides with
|
||||
// issueops.Reader.List and needs the second sentinel below.
|
||||
// Nothing calls its methods; identity is the whole point.
|
||||
|
|
@ -428,6 +433,9 @@ func (*roleAccessorSentinel) Reclaim(context.Context, issueops.ReclaimRequest) (
|
|||
func (*roleAccessorSentinel) Heartbeat(context.Context, issueops.HeartbeatRequest) (issueops.HeartbeatResult, error) {
|
||||
return issueops.HeartbeatResult{}, nil
|
||||
}
|
||||
func (*roleAccessorSentinel) ListBlocked(context.Context, issueops.BlockedRequest) (issueops.BlockedResult, error) {
|
||||
return issueops.BlockedResult{}, nil
|
||||
}
|
||||
|
||||
// memoryRoleSentinel is the memory role's sentinel, and the one role
|
||||
// memoryRoleSentinel is the remaining role's sentinel, and the one role
|
||||
|
|
@ -460,7 +468,7 @@ func (*memoryRoleSentinel) List(context.Context, memoryops.ListRequest) (memoryo
|
|||
// paragraph rather than four near-identical ones (bd-8ri3m). Reads fire no
|
||||
// completion hooks, so IssueReader, IssueRelations, Counter, StatsReporter,
|
||||
// CycleDetector, EdgeReader, BlockingAnnotator, TreeWalker, GraphCounter,
|
||||
// ReadyCounter, Querier and InitVerifier deliberately return the inner surface
|
||||
// ReadyCounter, BlockedLister, Querier and InitVerifier deliberately return the inner surface
|
||||
// unwrapped,
|
||||
// each in its own hook_*.go. The ones in that column that are NOT reads are
|
||||
// WorkspaceConfig, Memories, VersionReconciler, Bootstrapper, Sweeper,
|
||||
|
|
@ -511,6 +519,7 @@ func TestHookFiringStoreWrapsTheWriteRolesAndPassesTheReadsThrough(t *testing.T)
|
|||
{"Bootstrapper", func() (any, error) { return store.Bootstrapper() }, inner.bootstrapper, false},
|
||||
{"InitVerifier", func() (any, error) { return store.InitVerifier() }, inner.verifier, false},
|
||||
{"Heartbeater", func() (any, error) { return store.Heartbeater() }, inner.heartbeater, true},
|
||||
{"BlockedLister", func() (any, error) { return store.BlockedLister() }, inner.blockedLister, false},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
surface, err := test.got()
|
||||
|
|
@ -571,6 +580,7 @@ func TestHookFiringStoreRoleAccessorsPropagateInnerErrors(t *testing.T) {
|
|||
{"Bootstrapper", func() (any, error) { return store.Bootstrapper() }},
|
||||
{"InitVerifier", func() (any, error) { return store.InitVerifier() }},
|
||||
{"Heartbeater", func() (any, error) { return store.Heartbeater() }},
|
||||
{"BlockedLister", func() (any, error) { return store.BlockedLister() }},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if _, err := test.got(); !errors.Is(err, want) {
|
||||
|
|
|
|||
|
|
@ -397,6 +397,12 @@ type Storage interface {
|
|||
// it, and a server must take it off a peeled store. See
|
||||
// hook_heartbeater.go.
|
||||
Heartbeater() (issueops.Heartbeater, error)
|
||||
// BlockedLister returns the blocked-listing surface for this store: what
|
||||
// `bd blocked` prints. It is a READ role and its hook decorator passes it
|
||||
// through (hook_blocked_lister.go); the external-dependency decorator
|
||||
// overrides it so the listing names unsatisfied external blockers, as its
|
||||
// GetBlockedIssues does.
|
||||
BlockedLister() (issueops.BlockedLister, error)
|
||||
|
||||
// MoleculeStepper returns the advance-a-molecule surface for this store:
|
||||
// find a molecule's next ready step after one closed and, on request,
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ go_library(
|
|||
"batch_closer.go",
|
||||
"batch_creator.go",
|
||||
"batchgetter.go",
|
||||
"blocked_lister.go",
|
||||
"blocked_recheck.go",
|
||||
"blockingannotator.go",
|
||||
"bootstrapper.go",
|
||||
|
|
@ -100,6 +101,7 @@ go_test(
|
|||
"batch_closer_contract_test.go",
|
||||
"batch_creator_contract_test.go",
|
||||
"batch_getter_contract_test.go",
|
||||
"blocked_lister_contract_test.go",
|
||||
"blocked_recheck_race_test.go",
|
||||
"blocking_annotator_contract_test.go",
|
||||
"bootstrapper_contract_test.go",
|
||||
|
|
|
|||
50
internal/storage/uow/blocked_lister.go
Normal file
50
internal/storage/uow/blocked_lister.go
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
package uow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
storageissueops "github.com/steveyegge/beads/internal/storage/issueops"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// BlockedListerSource is the capability accessor a unit-of-work provider
|
||||
// offers for the blocked-listing role.
|
||||
type BlockedListerSource interface {
|
||||
BlockedLister() (publicops.BlockedLister, error)
|
||||
}
|
||||
|
||||
// blockedLister lists the blocked issues through a unit of work.
|
||||
type blockedLister struct {
|
||||
provider UnitOfWorkProvider
|
||||
}
|
||||
|
||||
// BlockedLister returns the blocked-listing surface for this provider.
|
||||
func (p *doltSQLProvider) BlockedLister() (publicops.BlockedLister, error) {
|
||||
return NewBlockedLister(p)
|
||||
}
|
||||
|
||||
// NewBlockedLister constructs a public BlockedLister backed by provider.
|
||||
func NewBlockedLister(provider UnitOfWorkProvider) (publicops.BlockedLister, error) {
|
||||
if isNilUnitOfWorkProvider(provider) {
|
||||
return nil, fmt.Errorf("new blocked lister: unit-of-work provider must not be nil")
|
||||
}
|
||||
return &blockedLister{provider: provider}, nil
|
||||
}
|
||||
|
||||
var _ publicops.BlockedLister = (*blockedLister)(nil)
|
||||
|
||||
// ListBlocked answers one blocked listing inside one read-only unit of work,
|
||||
// through the use case's GetBlockedIssues: the same body the store legs run
|
||||
// (issueops.GetBlockedIssuesInTx), and, under a provider that applies the
|
||||
// external-dependency policy, that provider's decoration of it.
|
||||
func (l *blockedLister) ListBlocked(ctx context.Context, req publicops.BlockedRequest) (publicops.BlockedResult, error) {
|
||||
filter := storageissueops.BlockedFilter(req)
|
||||
return RunTxRead(ctx, l.provider, func(ctx context.Context, uw UnitOfWork) (publicops.BlockedResult, error) {
|
||||
items, err := uw.IssueUseCase().GetBlockedIssues(ctx, filter)
|
||||
if err != nil {
|
||||
return publicops.BlockedResult{}, err
|
||||
}
|
||||
return storageissueops.BlockedResultOf(items), nil
|
||||
})
|
||||
}
|
||||
31
internal/storage/uow/blocked_lister_contract_test.go
Normal file
31
internal/storage/uow/blocked_lister_contract_test.go
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
package uow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/backend/conformance"
|
||||
)
|
||||
|
||||
// TestBlockedListerContract runs the BlockedLister contract against the
|
||||
// unit-of-work provider, through its own capability accessor.
|
||||
func TestBlockedListerContract(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
provider := newUOWRoleFixtureProvider(t, ctx, "blk")
|
||||
source, ok := provider.(BlockedListerSource)
|
||||
if !ok {
|
||||
t.Fatalf("provider %T does not offer the BlockedLister accessor", provider)
|
||||
}
|
||||
lister, err := source.BlockedLister()
|
||||
if err != nil {
|
||||
t.Fatalf("BlockedLister(): %v", err)
|
||||
}
|
||||
kit := newUOWRoleFixtureKit(provider, "blk")
|
||||
conformance.RunBlockedLister(t, ctx, conformance.BlockedListerFixture{
|
||||
IssuePrefix: kit.IssuePrefix,
|
||||
BlockedLister: lister,
|
||||
CreateIssue: kit.CreateIssue,
|
||||
CreateWisp: kit.CreateWisp,
|
||||
AddDependency: kit.AddDependency,
|
||||
})
|
||||
}
|
||||
|
|
@ -316,6 +316,12 @@ func (p *notifyingProvider) Heartbeater() (publicops.Heartbeater, error) {
|
|||
return NewHeartbeater(p)
|
||||
}
|
||||
|
||||
// BlockedLister builds the blocked listing over THIS provider. It is a read:
|
||||
// nothing is recorded and no hook fires.
|
||||
func (p *notifyingProvider) BlockedLister() (publicops.BlockedLister, error) {
|
||||
return NewBlockedLister(p)
|
||||
}
|
||||
|
||||
func (p *notifyingProvider) Memories() (memoryops.Memories, error) { return NewMemories(p) }
|
||||
|
||||
// EventsJournalCursor builds on THIS provider, like every role above it, so a
|
||||
|
|
@ -433,6 +439,7 @@ var (
|
|||
_ MemoriesSource = (*notifyingProvider)(nil)
|
||||
_ LeaseReclaimerSource = (*notifyingProvider)(nil)
|
||||
_ HeartbeaterSource = (*notifyingProvider)(nil)
|
||||
_ BlockedListerSource = (*notifyingProvider)(nil)
|
||||
_ EventsJournalCursorSource = (*notifyingProvider)(nil)
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ go_library(
|
|||
"batch_closer.go",
|
||||
"batch_creator.go",
|
||||
"batch_getter.go",
|
||||
"blocked_lister.go",
|
||||
"blockingannotator.go",
|
||||
"bootstrapper.go",
|
||||
"commenter.go",
|
||||
|
|
|
|||
38
internal/telemetry/blocked_lister.go
Normal file
38
internal/telemetry/blocked_lister.go
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// BlockedLister returns the inner store's blocked-listing surface wrapped in
|
||||
// this layer's instrumentation. It recurses instead of delegating: a blind
|
||||
// delegation would return the inner surface unspanned and untimed.
|
||||
func (s *InstrumentedStorage) BlockedLister() (issueops.BlockedLister, error) {
|
||||
inner, err := s.Unwrap().BlockedLister()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.WrapBlockedLister(inner), nil
|
||||
}
|
||||
|
||||
// WrapBlockedLister instruments the blocked listing with this storage layer's
|
||||
// existing telemetry meter and tracer. The external-dependency decorator
|
||||
// calls it on the lister it builds over itself, so the span survives that
|
||||
// override.
|
||||
func (s *InstrumentedStorage) WrapBlockedLister(inner issueops.BlockedLister) issueops.BlockedLister {
|
||||
return &instrumentedBlockedLister{storage: s, inner: inner}
|
||||
}
|
||||
|
||||
type instrumentedBlockedLister struct {
|
||||
storage *InstrumentedStorage
|
||||
inner issueops.BlockedLister
|
||||
}
|
||||
|
||||
func (c *instrumentedBlockedLister) ListBlocked(ctx context.Context, request issueops.BlockedRequest) (result issueops.BlockedResult, err error) {
|
||||
ctx, span, started := c.storage.op(ctx, "BlockedLister.ListBlocked")
|
||||
result, err = c.inner.ListBlocked(ctx, request)
|
||||
c.storage.done(ctx, span, started, err)
|
||||
return result, err
|
||||
}
|
||||
|
|
@ -94,7 +94,7 @@ func TestInstrumentedStorageDeclaresEveryRoleAccessor(t *testing.T) {
|
|||
}
|
||||
|
||||
// roleAccessorStore is a DoltStorage whose only real methods are the
|
||||
// thirty role accessors, each answering with a distinguishable sentinel
|
||||
// thirty-one role accessors, each answering with a distinguishable sentinel
|
||||
// so a test can tell an instrumented surface from a passed-through one.
|
||||
//
|
||||
// TWO sentinels rather than one: memoryops.Memories.List and issueops.Reader.List
|
||||
|
|
@ -181,8 +181,11 @@ func (s *roleAccessorStore) LeaseReclaimer() (issueops.LeaseReclaimer, error) {
|
|||
func (s *roleAccessorStore) Heartbeater() (issueops.Heartbeater, error) {
|
||||
return s.surface, s.err
|
||||
}
|
||||
func (s *roleAccessorStore) BlockedLister() (issueops.BlockedLister, error) {
|
||||
return s.surface, s.err
|
||||
}
|
||||
|
||||
// roleAccessorSentinel implements twenty-nine of the thirty roles at
|
||||
// roleAccessorSentinel implements thirty of the thirty-one roles at
|
||||
// once — every one but memoryops.Memories, whose List collides with
|
||||
// issueops.Reader.List and needs the second sentinel below.
|
||||
// Nothing calls its methods; identity is the whole point.
|
||||
|
|
@ -318,6 +321,9 @@ func (*roleAccessorSentinel) Reclaim(context.Context, issueops.ReclaimRequest) (
|
|||
func (*roleAccessorSentinel) Heartbeat(context.Context, issueops.HeartbeatRequest) (issueops.HeartbeatResult, error) {
|
||||
return issueops.HeartbeatResult{}, nil
|
||||
}
|
||||
func (*roleAccessorSentinel) ListBlocked(context.Context, issueops.BlockedRequest) (issueops.BlockedResult, error) {
|
||||
return issueops.BlockedResult{}, nil
|
||||
}
|
||||
|
||||
// memoryRoleSentinel is the memory role's sentinel — see
|
||||
// memoryRoleSentinel is the remaining role's sentinel — see
|
||||
|
|
@ -396,6 +402,7 @@ func TestInstrumentedStorageInstrumentsEveryRoleAccessor(t *testing.T) {
|
|||
{"Releaser", func() (any, error) { return wrapped.Releaser() }, sentinel},
|
||||
{"LeaseReclaimer", func() (any, error) { return wrapped.LeaseReclaimer() }, sentinel},
|
||||
{"Heartbeater", func() (any, error) { return wrapped.Heartbeater() }, sentinel},
|
||||
{"BlockedLister", func() (any, error) { return wrapped.BlockedLister() }, sentinel},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
surface, err := test.got()
|
||||
|
|
@ -419,9 +426,10 @@ func TestInstrumentedStorageInstrumentsEveryRoleAccessor(t *testing.T) {
|
|||
// turn, so an externaldeps override that skips it silently drops the
|
||||
// storage.ReadyCounter.CountReady span for every text-mode `bd ready`.
|
||||
//
|
||||
// This is the only test that wires a real decorator above the instrumented
|
||||
// store, which is why WrapReadyCounter's sole caller outside this package is
|
||||
// the thing being pinned here.
|
||||
// This and its blocked-listing twin below are the only tests that wire a real
|
||||
// decorator above the instrumented store, which is why WrapReadyCounter's and
|
||||
// WrapBlockedLister's sole callers outside this package are the things being
|
||||
// pinned here.
|
||||
func TestExternalDepsReadyCounterSurvivesThisLayer(t *testing.T) {
|
||||
t.Setenv("BD_OTEL_STDOUT", "true")
|
||||
inner := &roleAccessorStore{surface: &roleAccessorSentinel{}}
|
||||
|
|
@ -439,6 +447,29 @@ func TestExternalDepsReadyCounterSurvivesThisLayer(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestExternalDepsBlockedListerSurvivesThisLayer is the same pin for the
|
||||
// blocked listing. externaldeps builds a local store's lister over its own
|
||||
// GetBlockedIssues, so the listing carries the external blockers that read
|
||||
// adds, which leaves handing the finished lister to WrapBlockedLister as this
|
||||
// layer's only turn: an override that skips it silently drops the
|
||||
// storage.BlockedLister.ListBlocked span for every local `bd blocked`.
|
||||
func TestExternalDepsBlockedListerSurvivesThisLayer(t *testing.T) {
|
||||
t.Setenv("BD_OTEL_STDOUT", "true")
|
||||
inner := &roleAccessorStore{surface: &roleAccessorSentinel{}}
|
||||
instrumented, ok := WrapStorage(inner).(*InstrumentedStorage)
|
||||
if !ok {
|
||||
t.Fatal("WrapStorage did not instrument the store; telemetry is disabled in this environment")
|
||||
}
|
||||
|
||||
lister, err := externaldeps.New(instrumented, nil, nil).BlockedLister()
|
||||
if err != nil {
|
||||
t.Fatalf("externaldeps BlockedLister() error = %v", err)
|
||||
}
|
||||
if _, ok := lister.(*instrumentedBlockedLister); !ok {
|
||||
t.Fatalf("externaldeps BlockedLister() = %T, want it wrapped by this layer; the storage.BlockedLister.ListBlocked span stops being emitted for local bd blocked", lister)
|
||||
}
|
||||
}
|
||||
|
||||
// TestInstrumentedStorageRoleAccessorsPropagateInnerErrors pins the other half
|
||||
// of the recursion: an accessor that recurses must not swallow the inner
|
||||
// store's refusal, nor hand back a wrapper around nothing.
|
||||
|
|
@ -484,6 +515,7 @@ func TestInstrumentedStorageRoleAccessorsPropagateInnerErrors(t *testing.T) {
|
|||
{"Releaser", func() (any, error) { return wrapped.Releaser() }},
|
||||
{"LeaseReclaimer", func() (any, error) { return wrapped.LeaseReclaimer() }},
|
||||
{"Heartbeater", func() (any, error) { return wrapped.Heartbeater() }},
|
||||
{"BlockedLister", func() (any, error) { return wrapped.BlockedLister() }},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
surface, err := test.got()
|
||||
|
|
|
|||
|
|
@ -756,6 +756,36 @@ func TestReadyCounterExposesTypedUnsupportedError(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestBlockedListerKeepsTelemetryOutermost is the READ answer again: listing
|
||||
// the blocked set fires no completion hooks, so the hook decorator adds no
|
||||
// layer.
|
||||
func TestBlockedListerKeepsTelemetryOutermost(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")
|
||||
}
|
||||
|
||||
lister, err := storage.NewHookFiringStore(instrumented, nil).BlockedLister()
|
||||
if err != nil {
|
||||
t.Fatalf("BlockedLister() error = %v", err)
|
||||
}
|
||||
if got := reflect.TypeOf(lister).String(); got != "*telemetry.instrumentedBlockedLister" {
|
||||
t.Fatalf("outer layer = %s, want the telemetry wrapper unwrapped by the hook decorator", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlockedListerExposesTypedUnsupportedError(t *testing.T) {
|
||||
lister, err := (*dolt.DoltStore)(nil).BlockedLister()
|
||||
if lister != nil {
|
||||
t.Fatalf("BlockedLister() lister = %T, want nil", lister)
|
||||
}
|
||||
var unsupported *beads.ErrUnsupported
|
||||
if !errors.As(err, &unsupported) {
|
||||
t.Fatalf("BlockedLister() error = %v, want *beads.ErrUnsupported", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestQuerierKeepsTelemetryOutermost is the READ answer again: a query fires no
|
||||
// completion hooks, so the hook decorator adds no layer.
|
||||
func TestQuerierKeepsTelemetryOutermost(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ go_library(
|
|||
"batchcloser.go",
|
||||
"batchcreator.go",
|
||||
"batchgetter.go",
|
||||
"blockedlister.go",
|
||||
"blockedstate.go",
|
||||
"blockingannotator.go",
|
||||
"bootstrapper.go",
|
||||
|
|
|
|||
64
issueops/blockedlister.go
Normal file
64
issueops/blockedlister.go
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
package issueops
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// BlockedIssue is one row of the blocked listing: the issue, plus the ids of
|
||||
// the blockers bd names for it. It is the element type `bd blocked --json`
|
||||
// emits.
|
||||
type BlockedIssue = types.BlockedIssue
|
||||
|
||||
// BlockedRequest is the question `bd blocked` asks: which issues are blocked,
|
||||
// optionally narrowed by parent and labels.
|
||||
//
|
||||
// Its fields are the command's flags, one for one. Labels are normalized the
|
||||
// way every label filter is (trimmed, blanks and repeats dropped) on an
|
||||
// attempt-local copy; the caller's slices are never written.
|
||||
type BlockedRequest struct {
|
||||
// ParentID narrows to the parent's direct children (a parent-child edge)
|
||||
// and to ids under it in the dotted hierarchy. Empty means no narrowing.
|
||||
ParentID string
|
||||
// Labels must all be present (AND).
|
||||
Labels []string
|
||||
// LabelsAny needs at least one present (OR).
|
||||
LabelsAny []string
|
||||
// ExcludeLabels must all be absent.
|
||||
ExcludeLabels []string
|
||||
}
|
||||
|
||||
// BlockedResult is the blocked listing.
|
||||
type BlockedResult struct {
|
||||
// Items is ordered by priority ascending, then created_at descending,
|
||||
// then id. It is never nil: an empty listing is an empty slice, so a
|
||||
// front door that encodes it prints [] and never null.
|
||||
Items []*BlockedIssue
|
||||
}
|
||||
|
||||
// BlockedLister describes listing the blocked issues: what `bd blocked`
|
||||
// prints. Like Reader and ReadyCounter, it is a role with its own accessor. A
|
||||
// new capability gets a new role interface and its own accessor; never append
|
||||
// a method here.
|
||||
//
|
||||
// THE SET IS bd's BLOCKED DOOR, NOT THE RAW COLUMN. It is seeded from the
|
||||
// stored, transitively propagated is_blocked flag on both planes (issues and
|
||||
// wisps; closed and pinned-status rows excluded; no type exclusions), then
|
||||
// narrowed to rows bd can NAME a blocker for: an active blocks, waits-for or
|
||||
// conditional-blocks target resident in this workspace that is neither closed
|
||||
// nor pinned, else the parent. A row whose flag is set but which has neither
|
||||
// is not listed. Where the external-dependency policy applies, an unsatisfied
|
||||
// external: blocker is added to the row's blockers, and a row blocked only by
|
||||
// such refs is listed too, narrowed by the request's parent and label filters
|
||||
// like every other row.
|
||||
//
|
||||
// IT IS NOT A PAGE. There is no limit and no cursor, like the local command,
|
||||
// and an answer is never truncated.
|
||||
//
|
||||
// LISTING IS A READ. Nothing here records a history entry, fires a completion
|
||||
// hook or changes a row. Result values are unspecified when error is non-nil.
|
||||
type BlockedLister interface {
|
||||
// ListBlocked answers one blocked listing in one read.
|
||||
ListBlocked(ctx context.Context, req BlockedRequest) (BlockedResult, error)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue