feat(issueops): put bd status behind the StatsReporter role (bd-4ze25)
`bd status` (and its `bd stats` alias) had two implementations of the same command. The direct route asked the store for statistics and, under --assigned, built an assignee filter, ran a ready-work query and folded five status counts itself; status_proxied_server.go did all four again through a unit of work. Both now build an issueops request and ask for the role, and the difference between the two routes is which accessor answers. THE ROLE. Its numbers are DEPENDENCY-AWARE — the blocked count reads the denormalized transitive is_blocked flag and readiness is derived from it — so no predicate over the issues table describes them and this is its own role rather than a sixth Counter dimension, which is what issueops/ counter.go already said it would be. Stats and AssigneeStats are born together because they answer the same question of two sets; they are two METHODS rather than one with an Assignee field because the assignee answer fills four fields of the same struct by different definitions, and a request whose optional string silently changed what a number meant is the shape this programme exists to remove. WHAT THE LEAF DOC NOW SAYS OUT LOUD, none of it written down anywhere before: BlockedIssues counts the graph, not the "blocked" status; ReadyIssues is arithmetic and NOT the cardinality of `bd ready`; PinnedIssues overlaps every status bucket so the buckets do not sum to Total; the workspace-wide answer excludes the wisp tier while the assignee-scoped one merges it; --no-blocked is a HINT whose only report is BlockedIssues being nil; and EpicsEligibleForClosure and AverageLeadTime are structurally always zero, which is why `bd status`'s "Extended:" branch has never once printed. CONFORMANCE. backend/conformance/stats_reporter_contract.go holds thirteen cases, each citing the leaf doc by line, run at all three implementations with ZERO parks and zero divergences. Unusually for this suite they are THREE genuine votes: the two stores share the role body (storestats) but dolt/queries.go, embeddeddolt/statistics.go and domain/db/issue.go each spell the blocked count and the ready subtraction themselves. Every workspace-wide case asserts a before/after DELTA — a summary takes no predicate, so there is no IDFilter to scope it with the way the Counter contract scopes its cases. HTTP. GET /v0/beads/stats is added to the Tier-1 document FIRST and the types generated from it: a `Statistics` schema x-go-type-pinned to types.Statistics (checked: the pin survives, and the schema is now in the JSON-tag bijection test), a StatsResponse envelope mirroring the CLI's --json shape minus `recent_activity`, which no shipped path populates. The handler calls the same role both CLI routes call. `blocked_count_skipped` is DERIVED from the answer, never echoed from the request, because the hint is a hint. httpapi.Config's roles source grows a third field and requires it with the other two: a source that answers some operations and faults on others is not a source. ENFORCEMENT. cmd/bd/status.go and status_proxied_server.go no longer name types.IssueFilter or types.WorkFilter, so `status` LEAVES the forbidigo exception list (63 -> 61 of 388 files). The role-constructor depguard list gains storestats. TWO USER-VISIBLE CHANGES, both improvements and both small: `bd status --assigned` reports the underlying failure instead of the bare "failed to get assigned statistics", identically on both routes; and the proxied --no-blocked warning now fires from the ANSWER rather than from the route, so a backend that gains a fast path stops printing it with no edit. Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check clean (no codegen drift, whole httpapi package green); TestStatsReporterContract 13/13 at dolt, embeddeddolt and uow; TestEmbeddedStatus and TestProxiedServerStatus green with their gates set; TestProxiedLookup green; TestCorpusGolden green. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
270515915f
commit
c1c283e5ce
35 changed files with 2369 additions and 220 deletions
|
|
@ -163,6 +163,8 @@ linters:
|
|||
desc: "a command reaches the count role through store.Counter(), never through the constructor: the accessor is where each storage decorator adds its layer - see internal/workapi/storecounter/counter.go"
|
||||
- pkg: github.com/steveyegge/beads/internal/workapi/storeworkspaceconfig
|
||||
desc: "a command reaches the workspace-settings role through store.WorkspaceConfig(), never through the constructor: the accessor is where each storage decorator adds its layer - see internal/workapi/storeworkspaceconfig/workspaceconfig.go"
|
||||
- pkg: github.com/steveyegge/beads/internal/workapi/storestats
|
||||
desc: "a command reaches the summary role through store.StatsReporter(), never through the constructor: the accessor is where each storage decorator adds its layer - see internal/workapi/storestats/reporter.go"
|
||||
# The CONSTRUCTION half of that same boundary, and the half that actually
|
||||
# matches the failure. The depguard rule above denies a handler IMPORTING
|
||||
# the builders; it does not deny a handler naming the filter types, which
|
||||
|
|
@ -246,7 +248,7 @@ linters:
|
|||
linters:
|
||||
- forbidigo
|
||||
# Inside cmd/bd the rule is deny-by-default, so each entry below is a
|
||||
# HOLE in it and carries the reason that hole exists. 63 of the 382
|
||||
# HOLE in it and carries the reason that hole exists. 61 of the 388
|
||||
# non-test files under cmd/bd are on this list; widening it is an edit
|
||||
# here and a diff a reviewer sees. internal/httpapi has no entry and is
|
||||
# meant not to.
|
||||
|
|
@ -284,8 +286,15 @@ linters:
|
|||
# still named, and a new file in a family is still an edit here.
|
||||
#
|
||||
# Commands with a direct route and a proxied twin that build the same
|
||||
# filter on both:
|
||||
- path: '^cmd/bd/(close|duplicates|find_duplicates|gate|gc|graph|info|label|orphans|purge|search|status|todo|wisp)(_proxied_server)?\.go$'
|
||||
# filter on both.
|
||||
#
|
||||
# `status` LEFT this list when the StatsReporter role took the assignee
|
||||
# filter, the ready-work filter and the status fold off both its routes:
|
||||
# cmd/bd/status.go and cmd/bd/status_proxied_server.go now build an
|
||||
# issueops request and name no filter type, so the hole they needed is
|
||||
# closed rather than merely unused. Removing an entry here is how a role
|
||||
# commit proves its front doors reached the role.
|
||||
- path: '^cmd/bd/(close|duplicates|find_duplicates|gate|gc|graph|info|label|orphans|purge|search|todo|wisp)(_proxied_server)?\.go$'
|
||||
linters:
|
||||
- forbidigo
|
||||
# Molecule reporting: each selects the members of one molecule.
|
||||
|
|
|
|||
572
backend/conformance/stats_reporter_contract.go
Normal file
572
backend/conformance/stats_reporter_contract.go
Normal file
|
|
@ -0,0 +1,572 @@
|
|||
package conformance
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// This file holds the contract every implementation of
|
||||
// publicops.StatsReporter must satisfy. Each case asserts what
|
||||
// issueops/statsreporter.go PROMISES, cited by line, rather than what any one
|
||||
// backend happens to do today; a backend that disagrees is parked at its own
|
||||
// wiring site with skipKnownDivergence so the case still runs on the ones that
|
||||
// agree.
|
||||
//
|
||||
// THREE WIRINGS, AND HERE THAT REALLY IS THREE VOTES — which is unusual in
|
||||
// this suite and worth saying out loud, because the sibling contracts say the
|
||||
// opposite. For most roles dolt and embeddeddolt share one body
|
||||
// (internal/workapi/store*) and "both stores agree" is one vote plus an engine
|
||||
// check. That is still true of the ROLE layer here: both stores hand back
|
||||
// internal/workapi/storestats. But the queries it delegates to are written out
|
||||
// THREE times — dolt/queries.go, embeddeddolt/statistics.go and
|
||||
// domain/db/issue.go each spell the blocked count and the ready subtraction
|
||||
// themselves, and the two Dolt stores do not even agree on how many
|
||||
// transactions to spend (dolt takes two read transactions, embeddeddolt one).
|
||||
// Only the status tally is shared, through
|
||||
// internal/storage/issueops.ScanIssueCountsInTx. So a disagreement between the
|
||||
// two stores is reachable here in a way it is not for Counter.
|
||||
//
|
||||
// (There is a FOURTH copy of that arithmetic, unreachable: package-level
|
||||
// issueops.GetStatisticsInTx has no callers at all. Nothing here runs it.)
|
||||
//
|
||||
// EVERY WORKSPACE-WIDE CASE ASSERTS A DELTA, never an absolute. The summary
|
||||
// takes no predicate — that is the point of the role — so there is no IDFilter
|
||||
// to scope it with the way the Counter contract scopes its cases, and the
|
||||
// three fixtures each share one database with the other role suites that ran
|
||||
// before them. A before/after pair around a known seed is the only assertion
|
||||
// that is about THIS case's rows. The assignee-scoped cases are the exception
|
||||
// and do assert absolutes: each takes an assignee namespaced by the fixture
|
||||
// prefix, which no other case can seed.
|
||||
//
|
||||
// What is deliberately NOT here:
|
||||
// - the fold from an actor's rows to a summary, which is shared by all three
|
||||
// through internal/workapi.FoldStatsAssigneeSummary and pinned directly,
|
||||
// without a database, in internal/workapi/stats_test.go;
|
||||
// - the flag-to-request mapping, which is `bd status`'s job;
|
||||
// - whether the two halves of an assignee-scoped answer are one snapshot,
|
||||
// which statsreporter.go deliberately does not promise because the store
|
||||
// seam cannot offer it.
|
||||
|
||||
// StatsReporterFixture supplies adapter-specific storage access for the
|
||||
// summary assertions. Every field is named and typed exactly like the
|
||||
// per-backend roleFixtureKit hook it is filled from, so a wiring is kit plus
|
||||
// accessor plus prefix with no adapter in between.
|
||||
type StatsReporterFixture struct {
|
||||
// IssuePrefix namespaces the ids and the assignees each assertion seeds,
|
||||
// so several of them can share one database.
|
||||
IssuePrefix string
|
||||
StatsReporter publicops.StatsReporter
|
||||
// CreateIssue seeds a durable issue in the issues plane.
|
||||
CreateIssue func(context.Context, *types.Issue, string) error
|
||||
// CreateWisp seeds an ephemeral issue in the wisps plane. It is a separate
|
||||
// field rather than an Ephemeral flag on CreateIssue because the three
|
||||
// adapters reach the two planes through different verbs.
|
||||
CreateWisp func(context.Context, *types.Issue, string) error
|
||||
// AddDependency seeds ONE edge, which is how a case makes a row blocked:
|
||||
// the blocked count reads the denormalized is_blocked flag the edge insert
|
||||
// maintains, and there is no other way to set it through a public seam.
|
||||
AddDependency func(context.Context, *types.Dependency, string) error
|
||||
// CountHistory reports how many history entries the fixture's branch has.
|
||||
// A nil hook means "this backend cannot observe history", and the case
|
||||
// that needs it SKIPS with that reason rather than passing quietly.
|
||||
CountHistory func(context.Context) (int, error)
|
||||
}
|
||||
|
||||
// RunStatsReporterCountsEveryDurableRowByStatus pins statsreporter.go:92-98:
|
||||
// one scan of the durable plane, every row in Total including closed ones, and
|
||||
// PinnedIssues counting a flag that overlaps a status bucket rather than
|
||||
// naming a sixth status.
|
||||
//
|
||||
// The pinned row seeded here is OPEN, deliberately. A pinned row that was also
|
||||
// closed would leave "does pinned overlap or replace a status bucket"
|
||||
// unanswered, and that overlap is the clause a reader is most likely to get
|
||||
// wrong: the buckets do not sum to Total in either direction.
|
||||
func RunStatsReporterCountsEveryDurableRowByStatus(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
before := statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{})
|
||||
|
||||
seedStatsReporterIssue(t, ctx, fixture, statsReporterSeed(fixture, "by-status-open", types.StatusOpen))
|
||||
seedStatsReporterIssue(t, ctx, fixture, statsReporterSeed(fixture, "by-status-wip", types.StatusInProgress))
|
||||
seedStatsReporterIssue(t, ctx, fixture, statsReporterSeed(fixture, "by-status-closed", types.StatusClosed))
|
||||
seedStatsReporterIssue(t, ctx, fixture, statsReporterSeed(fixture, "by-status-deferred", types.StatusDeferred))
|
||||
pinned := statsReporterSeed(fixture, "by-status-pinned", types.StatusOpen)
|
||||
pinned.Pinned = true
|
||||
seedStatsReporterIssue(t, ctx, fixture, pinned)
|
||||
|
||||
after := statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{})
|
||||
assertStatsReporterDelta(t, before, after, statsReporterCounts{
|
||||
total: 5, open: 2, inProgress: 1, closed: 1, deferred: 1, pinned: 1,
|
||||
})
|
||||
}
|
||||
|
||||
// RunStatsReporterExcludesTheWispTier pins statsreporter.go:116-119: the
|
||||
// workspace-wide answer counts the durable plane only.
|
||||
//
|
||||
// It is the same A/B the Counter contract runs on its own default, and for the
|
||||
// same reason: the storage seam MERGES the two planes unless told not to, so
|
||||
// "durable only" is an active decision on every summary rather than something
|
||||
// that falls out of doing nothing. The assignee-scoped case below is the other
|
||||
// half of the pair — the two methods answer differently here, and that is the
|
||||
// contract.
|
||||
func RunStatsReporterExcludesTheWispTier(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
before := statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{})
|
||||
|
||||
seedStatsReporterIssue(t, ctx, fixture, statsReporterSeed(fixture, "plane-durable", types.StatusOpen))
|
||||
wisp := statsReporterSeed(fixture, "plane-wisp", types.StatusOpen)
|
||||
wisp.Ephemeral = true
|
||||
seedStatsReporterWisp(t, ctx, fixture, wisp)
|
||||
|
||||
after := statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{})
|
||||
assertStatsReporterDelta(t, before, after, statsReporterCounts{total: 1, open: 1})
|
||||
}
|
||||
|
||||
// RunStatsReporterAStatusOutsideTheTalliesIsCountedOnlyInTotal pins the second
|
||||
// half of statsreporter.go:92-98 — the tallies are exact equality against the
|
||||
// stored status, so a row whose status is none of the four lands in Total and
|
||||
// in no bucket, and the buckets do not sum to Total.
|
||||
//
|
||||
// It uses the "blocked" STATUS to do it, which makes this case do double duty:
|
||||
// that row is also the control for the case below. It has no dependency edge,
|
||||
// so its is_blocked flag is 0 and it must NOT move BlockedIssues either. A
|
||||
// backend that counted the status instead of the flag fails here, at the seed
|
||||
// that looks least like a blocked issue.
|
||||
func RunStatsReporterAStatusOutsideTheTalliesIsCountedOnlyInTotal(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
before := statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{})
|
||||
|
||||
seedStatsReporterIssue(t, ctx, fixture, statsReporterSeed(fixture, "status-blocked", types.StatusBlocked))
|
||||
|
||||
after := statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{})
|
||||
assertStatsReporterDelta(t, before, after, statsReporterCounts{total: 1})
|
||||
}
|
||||
|
||||
// RunStatsReporterBlockedCountsTheGraphNotTheStatus pins
|
||||
// statsreporter.go:99-102: BlockedIssues counts rows whose transitive
|
||||
// is_blocked flag is set, and an open row with an unfinished blocker is one of
|
||||
// them while its status is still "open".
|
||||
//
|
||||
// Both seeded rows are OPEN, so the case fails in an unmistakable way if a
|
||||
// backend ever counted the status: the delta it would report is zero blocked
|
||||
// out of two open rows.
|
||||
func RunStatsReporterBlockedCountsTheGraphNotTheStatus(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
before := statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{})
|
||||
|
||||
blocker := statsReporterSeed(fixture, "graph-blocker", types.StatusOpen)
|
||||
blocked := statsReporterSeed(fixture, "graph-blocked", types.StatusOpen)
|
||||
seedStatsReporterIssue(t, ctx, fixture, blocker)
|
||||
seedStatsReporterIssue(t, ctx, fixture, blocked)
|
||||
blockStatsReporterIssue(t, ctx, fixture, blocked.ID, blocker.ID)
|
||||
|
||||
after := statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{})
|
||||
assertStatsReporterDelta(t, before, after, statsReporterCounts{total: 2, open: 2, blocked: 1})
|
||||
}
|
||||
|
||||
// RunStatsReporterReadyIsOpenMinusBlocked pins statsreporter.go:103-108:
|
||||
// ReadyIssues is arithmetic over two numbers in the same answer, not a query.
|
||||
//
|
||||
// The identity is asserted on the ABSOLUTE summary rather than on a delta,
|
||||
// because it is a property of every answer this role gives and not of the rows
|
||||
// this case seeded. The seed is here so the three numbers are not trivially
|
||||
// equal: without a blocked row, Ready == Open would hold under an
|
||||
// implementation that never subtracted anything.
|
||||
func RunStatsReporterReadyIsOpenMinusBlocked(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
blocker := statsReporterSeed(fixture, "arith-blocker", types.StatusOpen)
|
||||
blocked := statsReporterSeed(fixture, "arith-blocked", types.StatusOpen)
|
||||
seedStatsReporterIssue(t, ctx, fixture, blocker)
|
||||
seedStatsReporterIssue(t, ctx, fixture, blocked)
|
||||
blockStatsReporterIssue(t, ctx, fixture, blocked.ID, blocker.ID)
|
||||
|
||||
summary := statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{})
|
||||
blockedCount := statsReporterPointer(t, "BlockedIssues", summary.BlockedIssues)
|
||||
ready := statsReporterPointer(t, "ReadyIssues", summary.ReadyIssues)
|
||||
|
||||
want := summary.OpenIssues - blockedCount
|
||||
if want < 0 {
|
||||
want = 0
|
||||
}
|
||||
if ready != want {
|
||||
t.Fatalf("ReadyIssues = %d, want OpenIssues(%d) - BlockedIssues(%d) clamped at zero = %d",
|
||||
ready, summary.OpenIssues, blockedCount, want)
|
||||
}
|
||||
if blockedCount < 1 {
|
||||
t.Fatalf("BlockedIssues = %d after seeding a blocked row; the identity above held vacuously", blockedCount)
|
||||
}
|
||||
}
|
||||
|
||||
// RunStatsReporterSkipBlockedPairsTheTwoPointers pins the whole of the
|
||||
// SkipBlocked promise (statsreporter.go:138-154), which is stated from the
|
||||
// ANSWER's side because the backends genuinely differ on whether they can take
|
||||
// the hint:
|
||||
//
|
||||
// - the two pointers are nil together or populated together, never one of
|
||||
// each — every front door renders on exactly that pairing;
|
||||
// - nothing else in the summary changes;
|
||||
// - a populated pair means the hint was not taken, which is a legal answer
|
||||
// and not a failure.
|
||||
//
|
||||
// So this case does NOT assert that the fast path was used. It asserts what a
|
||||
// caller may rely on regardless, on all three backends, with no park. Today
|
||||
// the two store backends take the hint (GetStatisticsNoBlocked) and the
|
||||
// unit-of-work backend does not (domain.IssueUseCase publishes no no-blocked
|
||||
// query); a reader wanting to know which is which reads the wiring, not this
|
||||
// case.
|
||||
func RunStatsReporterSkipBlockedPairsTheTwoPointers(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
seedStatsReporterIssue(t, ctx, fixture, statsReporterSeed(fixture, "hint-open", types.StatusOpen))
|
||||
|
||||
full := statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{})
|
||||
skipped := statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{SkipBlocked: true})
|
||||
|
||||
if (skipped.BlockedIssues == nil) != (skipped.ReadyIssues == nil) {
|
||||
t.Fatalf("SkipBlocked answered with BlockedIssues=%v and ReadyIssues=%v; readiness is derived from the blocked count, so the two are nil together or populated together",
|
||||
skipped.BlockedIssues, skipped.ReadyIssues)
|
||||
}
|
||||
if skipped.BlockedIssues != nil {
|
||||
if got, want := *skipped.BlockedIssues, statsReporterPointer(t, "BlockedIssues", full.BlockedIssues); got != want {
|
||||
t.Errorf("SkipBlocked was not taken and reported BlockedIssues = %d, want the full answer's %d", got, want)
|
||||
}
|
||||
if got, want := *skipped.ReadyIssues, statsReporterPointer(t, "ReadyIssues", full.ReadyIssues); got != want {
|
||||
t.Errorf("SkipBlocked was not taken and reported ReadyIssues = %d, want the full answer's %d", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing else moves. Compared against the full call taken immediately
|
||||
// before, on a fixture only this suite writes to.
|
||||
assertStatsReporterDelta(t, full, skipped, statsReporterCounts{})
|
||||
}
|
||||
|
||||
// RunStatsReporterExtendedFieldsAreAlwaysZero pins statsreporter.go:109-114:
|
||||
// EpicsEligibleForClosure and AverageLeadTime are always zero because no
|
||||
// implementation computes either.
|
||||
//
|
||||
// It is a tripwire rather than a behavior test, and it is worth a case
|
||||
// precisely because it can only fail on GOOD news: the day a backend starts
|
||||
// computing one of them, this fails and the doc that calls it always zero — and
|
||||
// the `bd status` render branch that has never fired — get revisited in the
|
||||
// same change rather than left saying something false.
|
||||
func RunStatsReporterExtendedFieldsAreAlwaysZero(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
summary := statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{})
|
||||
if summary.EpicsEligibleForClosure != 0 {
|
||||
t.Errorf("EpicsEligibleForClosure = %d; statsreporter.go promises it is always zero because nothing computes it",
|
||||
summary.EpicsEligibleForClosure)
|
||||
}
|
||||
if summary.AverageLeadTime != 0 {
|
||||
t.Errorf("AverageLeadTime = %v; statsreporter.go promises it is always zero because nothing computes it",
|
||||
summary.AverageLeadTime)
|
||||
}
|
||||
}
|
||||
|
||||
// RunStatsReporterWritesNothing pins statsreporter.go:121-125: reporting is a
|
||||
// read, so neither method records a history entry.
|
||||
//
|
||||
// The delta is taken around BOTH methods together. An absolute count would be
|
||||
// meaningless on a fixture other cases have already seeded, and the seeds this
|
||||
// case needs are taken before the first reading for the same reason.
|
||||
func RunStatsReporterWritesNothing(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
if fixture.CountHistory == nil {
|
||||
t.Skip("this backend cannot observe history, so the read-only clause cannot be checked here")
|
||||
}
|
||||
assignee := statsReporterAssignee(fixture, "writes-nothing")
|
||||
seed := statsReporterSeed(fixture, "writes-nothing", types.StatusOpen)
|
||||
seed.Assignee = assignee
|
||||
seedStatsReporterIssue(t, ctx, fixture, seed)
|
||||
|
||||
before, err := fixture.CountHistory(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("CountHistory before: %v", err)
|
||||
}
|
||||
|
||||
statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{})
|
||||
statsReporterSummary(t, ctx, fixture, publicops.StatsRequest{SkipBlocked: true})
|
||||
statsReporterAssigneeSummary(t, ctx, fixture, assignee)
|
||||
|
||||
after, err := fixture.CountHistory(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("CountHistory after: %v", err)
|
||||
}
|
||||
if after != before {
|
||||
t.Fatalf("history entries went %d -> %d across three summary reads, want no change", before, after)
|
||||
}
|
||||
}
|
||||
|
||||
// RunStatsReporterAssigneeStatsScopesToOneActor pins the first and last
|
||||
// bullets of statsreporter.go:159-179: the answer is one actor's rows, and
|
||||
// PinnedIssues is always zero on this path along with the two fields that are
|
||||
// always zero everywhere.
|
||||
//
|
||||
// The assignee is namespaced by the fixture prefix, so this case can assert
|
||||
// ABSOLUTE numbers where the workspace-wide cases cannot: no other case in any
|
||||
// role suite can seed a row for it.
|
||||
func RunStatsReporterAssigneeStatsScopesToOneActor(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
mine := statsReporterAssignee(fixture, "scope-mine")
|
||||
theirs := statsReporterAssignee(fixture, "scope-theirs")
|
||||
|
||||
for _, seed := range []struct {
|
||||
suffix string
|
||||
status types.Status
|
||||
assignee string
|
||||
pinned bool
|
||||
}{
|
||||
{"scope-open", types.StatusOpen, mine, false},
|
||||
{"scope-pinned", types.StatusOpen, mine, true},
|
||||
{"scope-closed", types.StatusClosed, mine, false},
|
||||
{"scope-other", types.StatusOpen, theirs, false},
|
||||
} {
|
||||
issue := statsReporterSeed(fixture, seed.suffix, seed.status)
|
||||
issue.Assignee = seed.assignee
|
||||
issue.Pinned = seed.pinned
|
||||
seedStatsReporterIssue(t, ctx, fixture, issue)
|
||||
}
|
||||
|
||||
summary := statsReporterAssigneeSummary(t, ctx, fixture, mine)
|
||||
if summary.TotalIssues != 3 {
|
||||
t.Errorf("TotalIssues = %d, want 3 — the other actor's row is not this actor's work", summary.TotalIssues)
|
||||
}
|
||||
if summary.OpenIssues != 2 {
|
||||
t.Errorf("OpenIssues = %d, want 2", summary.OpenIssues)
|
||||
}
|
||||
if summary.ClosedIssues != 1 {
|
||||
t.Errorf("ClosedIssues = %d, want 1 — an assignee summary counts closed rows too", summary.ClosedIssues)
|
||||
}
|
||||
if summary.PinnedIssues != 0 {
|
||||
t.Errorf("PinnedIssues = %d, want 0 — the assignee fold tallies the five statuses and nothing else, even with a pinned row in the set", summary.PinnedIssues)
|
||||
}
|
||||
if summary.EpicsEligibleForClosure != 0 || summary.AverageLeadTime != 0 {
|
||||
t.Errorf("extended fields = %d/%v, want zeros", summary.EpicsEligibleForClosure, summary.AverageLeadTime)
|
||||
}
|
||||
}
|
||||
|
||||
// RunStatsReporterAssigneeBlockedCountsTheStatusNotTheGraph pins the exact
|
||||
// INVERSE of the workspace-wide blocked clause, which is the sharpest
|
||||
// statement this contract makes: statsreporter.go:169-172 says an
|
||||
// assignee-scoped BlockedIssues counts rows whose STATUS is "blocked", where
|
||||
// the workspace-wide one counts the is_blocked flag.
|
||||
//
|
||||
// Both seeds belong to the same actor. One has the status and no edge; the
|
||||
// other has an edge and the status "open". The answer must be 1, and the two
|
||||
// backends' bodies can only get it right by using the fold rather than the
|
||||
// aggregate.
|
||||
func RunStatsReporterAssigneeBlockedCountsTheStatusNotTheGraph(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
assignee := statsReporterAssignee(fixture, "abl")
|
||||
|
||||
byStatus := statsReporterSeed(fixture, "abl-status", types.StatusBlocked)
|
||||
byStatus.Assignee = assignee
|
||||
seedStatsReporterIssue(t, ctx, fixture, byStatus)
|
||||
|
||||
blocker := statsReporterSeed(fixture, "abl-blocker", types.StatusOpen)
|
||||
blocker.Assignee = assignee
|
||||
byGraph := statsReporterSeed(fixture, "abl-graph", types.StatusOpen)
|
||||
byGraph.Assignee = assignee
|
||||
seedStatsReporterIssue(t, ctx, fixture, blocker)
|
||||
seedStatsReporterIssue(t, ctx, fixture, byGraph)
|
||||
blockStatsReporterIssue(t, ctx, fixture, byGraph.ID, blocker.ID)
|
||||
|
||||
summary := statsReporterAssigneeSummary(t, ctx, fixture, assignee)
|
||||
if got := statsReporterPointer(t, "BlockedIssues", summary.BlockedIssues); got != 1 {
|
||||
t.Errorf("BlockedIssues = %d, want 1: the row with status \"blocked\" and not the open row an edge blocks", got)
|
||||
}
|
||||
if summary.OpenIssues != 2 {
|
||||
t.Errorf("OpenIssues = %d, want 2 — a graph-blocked row keeps its status", summary.OpenIssues)
|
||||
}
|
||||
}
|
||||
|
||||
// RunStatsReporterAssigneeStatsMergesTheWispTier pins the first bullet of
|
||||
// statsreporter.go:163-168: this answer's set spans the durable plane AND the
|
||||
// ephemeral tier, where the workspace-wide answer is durable-only. It is the
|
||||
// other half of the A/B RunStatsReporterExcludesTheWispTier starts.
|
||||
func RunStatsReporterAssigneeStatsMergesTheWispTier(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
assignee := statsReporterAssignee(fixture, "amerge")
|
||||
|
||||
durable := statsReporterSeed(fixture, "amerge-durable", types.StatusOpen)
|
||||
durable.Assignee = assignee
|
||||
seedStatsReporterIssue(t, ctx, fixture, durable)
|
||||
|
||||
wisp := statsReporterSeed(fixture, "amerge-wisp", types.StatusOpen)
|
||||
wisp.Assignee = assignee
|
||||
wisp.Ephemeral = true
|
||||
seedStatsReporterWisp(t, ctx, fixture, wisp)
|
||||
|
||||
summary := statsReporterAssigneeSummary(t, ctx, fixture, assignee)
|
||||
if summary.TotalIssues != 2 {
|
||||
t.Errorf("TotalIssues = %d, want 2 — the actor's wisp is in this answer even though it is in no workspace-wide one", summary.TotalIssues)
|
||||
}
|
||||
if summary.OpenIssues != 2 {
|
||||
t.Errorf("OpenIssues = %d, want 2", summary.OpenIssues)
|
||||
}
|
||||
}
|
||||
|
||||
// RunStatsReporterAssigneeStatsPopulatesBothPointers pins the clause
|
||||
// FoldStatsAssigneeSummary exists to guarantee: on this path BlockedIssues and
|
||||
// ReadyIssues are ALWAYS non-nil, including for an actor with no rows at all.
|
||||
//
|
||||
// The nil pointers are the workspace-wide answer's skipped-scan signal and
|
||||
// every front door renders them as "(skipped)". An assignee summary skips
|
||||
// nothing, so a nil here would print a lie about a query that ran.
|
||||
func RunStatsReporterAssigneeStatsPopulatesBothPointers(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
summary := statsReporterAssigneeSummary(t, ctx, fixture, statsReporterAssignee(fixture, "nobody"))
|
||||
|
||||
if summary.TotalIssues != 0 {
|
||||
t.Fatalf("TotalIssues = %d for an actor with no rows, want 0", summary.TotalIssues)
|
||||
}
|
||||
if got := statsReporterPointer(t, "BlockedIssues", summary.BlockedIssues); got != 0 {
|
||||
t.Errorf("BlockedIssues = %d, want a populated 0", got)
|
||||
}
|
||||
if got := statsReporterPointer(t, "ReadyIssues", summary.ReadyIssues); got != 0 {
|
||||
t.Errorf("ReadyIssues = %d, want a populated 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// RunStatsReporterAssigneeStatsRefusesAnEmptyAssignee pins
|
||||
// statsreporter.go:46-51: an empty or whitespace-only assignee is
|
||||
// ErrValidation rather than a query for the rows whose assignee column is
|
||||
// empty.
|
||||
//
|
||||
// The whitespace case is the one that matters. An implementation that checked
|
||||
// `assignee == ""` would pass the first and answer the second with a summary
|
||||
// of nothing, which reads exactly like an actor who has no work.
|
||||
func RunStatsReporterAssigneeStatsRefusesAnEmptyAssignee(t *testing.T, ctx context.Context, fixture StatsReporterFixture) {
|
||||
t.Helper()
|
||||
for _, blank := range []string{"", " ", "\t"} {
|
||||
_, err := fixture.StatsReporter.AssigneeStats(ctx, publicops.AssigneeStatsRequest{Assignee: blank})
|
||||
if !errors.Is(err, publicops.ErrValidation) {
|
||||
t.Errorf("AssigneeStats(%q) error = %v, want ErrValidation", blank, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// statsReporterCounts is the delta a workspace-wide case expects. Every field
|
||||
// is named so a failure reads as "OpenIssues moved by 2, want 1" rather than
|
||||
// as two summaries a reader has to diff.
|
||||
type statsReporterCounts struct {
|
||||
total int
|
||||
open int
|
||||
inProgress int
|
||||
closed int
|
||||
deferred int
|
||||
pinned int
|
||||
blocked int
|
||||
}
|
||||
|
||||
// assertStatsReporterDelta compares two summaries field by field against the
|
||||
// movement a case seeded.
|
||||
//
|
||||
// The blocked delta is only checked when BOTH summaries carry the number: a
|
||||
// skipped scan reports nil, and the pairing case above is where that is
|
||||
// asserted. Ready is not checked here at all — it is arithmetic over two
|
||||
// fields this function already compares, and
|
||||
// RunStatsReporterReadyIsOpenMinusBlocked pins the arithmetic itself.
|
||||
func assertStatsReporterDelta(t *testing.T, before, after types.Statistics, want statsReporterCounts) {
|
||||
t.Helper()
|
||||
for _, field := range []struct {
|
||||
name string
|
||||
before, after int
|
||||
want int
|
||||
}{
|
||||
{"TotalIssues", before.TotalIssues, after.TotalIssues, want.total},
|
||||
{"OpenIssues", before.OpenIssues, after.OpenIssues, want.open},
|
||||
{"InProgressIssues", before.InProgressIssues, after.InProgressIssues, want.inProgress},
|
||||
{"ClosedIssues", before.ClosedIssues, after.ClosedIssues, want.closed},
|
||||
{"DeferredIssues", before.DeferredIssues, after.DeferredIssues, want.deferred},
|
||||
{"PinnedIssues", before.PinnedIssues, after.PinnedIssues, want.pinned},
|
||||
} {
|
||||
if got := field.after - field.before; got != field.want {
|
||||
t.Errorf("%s moved by %d (%d -> %d), want %d", field.name, got, field.before, field.after, field.want)
|
||||
}
|
||||
}
|
||||
if before.BlockedIssues != nil && after.BlockedIssues != nil {
|
||||
if got := *after.BlockedIssues - *before.BlockedIssues; got != want.blocked {
|
||||
t.Errorf("BlockedIssues moved by %d (%d -> %d), want %d",
|
||||
got, *before.BlockedIssues, *after.BlockedIssues, want.blocked)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// statsReporterSeed builds one issue with the fixture's prefix on its id, so
|
||||
// several cases can share a database.
|
||||
func statsReporterSeed(fixture StatsReporterFixture, suffix string, status types.Status) *types.Issue {
|
||||
id := fixture.IssuePrefix + "-" + suffix
|
||||
return &types.Issue{
|
||||
ID: id,
|
||||
Title: id,
|
||||
Status: status,
|
||||
Priority: 2,
|
||||
IssueType: types.TypeTask,
|
||||
}
|
||||
}
|
||||
|
||||
// statsReporterAssignee namespaces an actor to this fixture, which is what
|
||||
// lets the assignee-scoped cases assert absolute numbers.
|
||||
func statsReporterAssignee(fixture StatsReporterFixture, suffix string) string {
|
||||
return fixture.IssuePrefix + "-actor-" + suffix
|
||||
}
|
||||
|
||||
func seedStatsReporterIssue(t *testing.T, ctx context.Context, fixture StatsReporterFixture, issue *types.Issue) {
|
||||
t.Helper()
|
||||
if err := fixture.CreateIssue(ctx, issue, "conformance"); err != nil {
|
||||
t.Fatalf("seed issue %s: %v", issue.ID, err)
|
||||
}
|
||||
}
|
||||
|
||||
func seedStatsReporterWisp(t *testing.T, ctx context.Context, fixture StatsReporterFixture, issue *types.Issue) {
|
||||
t.Helper()
|
||||
if err := fixture.CreateWisp(ctx, issue, "conformance"); err != nil {
|
||||
t.Fatalf("seed wisp %s: %v", issue.ID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// blockStatsReporterIssue makes issueID blocked by dependsOnID. The edge is
|
||||
// the only public way to set the denormalized flag the workspace-wide blocked
|
||||
// count reads.
|
||||
func blockStatsReporterIssue(t *testing.T, ctx context.Context, fixture StatsReporterFixture, issueID, dependsOnID string) {
|
||||
t.Helper()
|
||||
if err := fixture.AddDependency(ctx, &types.Dependency{
|
||||
IssueID: issueID,
|
||||
DependsOnID: dependsOnID,
|
||||
Type: types.DepBlocks,
|
||||
}, "conformance"); err != nil {
|
||||
t.Fatalf("block %s on %s: %v", issueID, dependsOnID, err)
|
||||
}
|
||||
}
|
||||
|
||||
func statsReporterSummary(t *testing.T, ctx context.Context, fixture StatsReporterFixture, req publicops.StatsRequest) types.Statistics {
|
||||
t.Helper()
|
||||
result, err := fixture.StatsReporter.Stats(ctx, req)
|
||||
if err != nil {
|
||||
t.Fatalf("Stats(%+v): %v", req, err)
|
||||
}
|
||||
return result.Summary
|
||||
}
|
||||
|
||||
func statsReporterAssigneeSummary(t *testing.T, ctx context.Context, fixture StatsReporterFixture, assignee string) types.Statistics {
|
||||
t.Helper()
|
||||
result, err := fixture.StatsReporter.AssigneeStats(ctx, publicops.AssigneeStatsRequest{Assignee: assignee})
|
||||
if err != nil {
|
||||
t.Fatalf("AssigneeStats(%q): %v", assignee, err)
|
||||
}
|
||||
return result.Summary
|
||||
}
|
||||
|
||||
// statsReporterPointer reads one of the two nullable counts, failing loudly
|
||||
// when it is absent. A case that dereferenced it directly would panic on a
|
||||
// backend that answered nil, and the panic would name this file rather than
|
||||
// the clause that was broken.
|
||||
func statsReporterPointer(t *testing.T, name string, value *int) int {
|
||||
t.Helper()
|
||||
if value == nil {
|
||||
t.Fatalf("%s is nil on a summary that computed it", name)
|
||||
}
|
||||
return *value
|
||||
}
|
||||
105
cmd/bd/status.go
105
cmd/bd/status.go
|
|
@ -8,6 +8,7 @@ import (
|
|||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// StatusOutput represents the complete status output
|
||||
|
|
@ -76,42 +77,57 @@ Examples:
|
|||
jsonOutput = true
|
||||
}
|
||||
|
||||
if usesProxiedServer() {
|
||||
if noBlocked {
|
||||
fmt.Fprintln(os.Stderr, "warning: --no-blocked is not supported in proxied-server mode; running the full blocked-count query")
|
||||
}
|
||||
return runStatusProxiedServer(rootCtx, showAssigned, noActivity)
|
||||
}
|
||||
|
||||
ctx := rootCtx
|
||||
|
||||
var stats *types.Statistics
|
||||
var err error
|
||||
if noBlocked {
|
||||
stats, err = store.GetStatisticsNoBlocked(ctx)
|
||||
} else {
|
||||
stats, err = store.GetStatistics(ctx)
|
||||
}
|
||||
reporter, err := openStatsReporter()
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
|
||||
var result issueops.StatsResult
|
||||
if showAssigned {
|
||||
stats = getAssignedStatistics(actor)
|
||||
if stats == nil {
|
||||
return HandleErrorRespectJSON("failed to get assigned statistics")
|
||||
// --no-blocked is not consulted here, and never was: an
|
||||
// assignee-scoped summary computes both numbers by a route that has
|
||||
// no fast path (issueops.StatsReporter.AssigneeStats).
|
||||
result, err = reporter.AssigneeStats(rootCtx, issueops.AssigneeStatsRequest{Assignee: actor})
|
||||
} else {
|
||||
result, err = reporter.Stats(rootCtx, issueops.StatsRequest{SkipBlocked: noBlocked})
|
||||
if err == nil && noBlocked && result.Summary.BlockedIssues != nil {
|
||||
// The hint is a hint, and this is where a caller who asked for
|
||||
// the fast path finds out it was not available. It is derived
|
||||
// from the ANSWER rather than from the route: the two routes
|
||||
// differ on it today (the unit-of-work seam publishes no
|
||||
// no-blocked query), and a backend that gains one stops
|
||||
// printing this without an edit here.
|
||||
fmt.Fprintln(os.Stderr, "warning: this backend has no --no-blocked fast path; the full blocked-count query ran")
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
|
||||
var recentActivity *RecentActivitySummary
|
||||
if !noActivity {
|
||||
recentActivity = getGitActivity(24)
|
||||
}
|
||||
|
||||
return renderStatus(stats, recentActivity)
|
||||
return renderStatus(&result.Summary, recentActivity)
|
||||
},
|
||||
}
|
||||
|
||||
// openStatsReporter hands back the summary role for whichever route this
|
||||
// invocation is on, each through its OWN capability accessor — the store's for
|
||||
// the direct route and the provider's for the proxied one.
|
||||
//
|
||||
// Neither branch builds a filter, folds a summary or opens a unit of work.
|
||||
// That is the whole of what moved behind the role: this command used to hold
|
||||
// the assignee filter, the ready-work filter and the status fold on the direct
|
||||
// route, and a second copy of all three on the proxied one.
|
||||
func openStatsReporter() (issueops.StatsReporter, error) {
|
||||
if usesProxiedServer() {
|
||||
return proxiedStatsReporter()
|
||||
}
|
||||
return store.StatsReporter()
|
||||
}
|
||||
|
||||
func renderStatus(stats *types.Statistics, recentActivity *RecentActivitySummary) error {
|
||||
output := &StatusOutput{
|
||||
Summary: stats,
|
||||
|
|
@ -186,55 +202,6 @@ func getGitActivity(_ int) *RecentActivitySummary {
|
|||
return nil
|
||||
}
|
||||
|
||||
// getAssignedStatistics returns statistics for issues assigned to a specific user
|
||||
func getAssignedStatistics(assignee string) *types.Statistics {
|
||||
if store == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx := rootCtx
|
||||
|
||||
assigneePtr := assignee
|
||||
issues, err := store.SearchIssues(ctx, "", types.IssueFilter{Assignee: &assigneePtr})
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
readyCount := 0
|
||||
readyIssues, err := store.GetReadyWork(ctx, types.WorkFilter{Assignee: &assigneePtr})
|
||||
if err == nil {
|
||||
readyCount = len(readyIssues)
|
||||
}
|
||||
|
||||
return buildAssignedStats(issues, readyCount)
|
||||
}
|
||||
|
||||
func buildAssignedStats(issues []*types.Issue, readyCount int) *types.Statistics {
|
||||
stats := &types.Statistics{
|
||||
TotalIssues: len(issues),
|
||||
}
|
||||
|
||||
// Count by status
|
||||
blockedCount := 0
|
||||
for _, issue := range issues {
|
||||
switch issue.Status {
|
||||
case types.StatusOpen:
|
||||
stats.OpenIssues++
|
||||
case types.StatusInProgress:
|
||||
stats.InProgressIssues++
|
||||
case types.StatusBlocked:
|
||||
blockedCount++
|
||||
case types.StatusDeferred:
|
||||
stats.DeferredIssues++
|
||||
case types.StatusClosed:
|
||||
stats.ClosedIssues++
|
||||
}
|
||||
}
|
||||
stats.BlockedIssues = &blockedCount
|
||||
stats.ReadyIssues = &readyCount
|
||||
return stats
|
||||
}
|
||||
|
||||
func init() {
|
||||
statusCmd.Flags().Bool("all", false, "Show all issues (default behavior)")
|
||||
statusCmd.Flags().Bool("assigned", false, "Show issues assigned to current user")
|
||||
|
|
|
|||
|
|
@ -1,51 +1,35 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/uow"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
func runStatusProxiedServer(ctx context.Context, showAssigned, noActivity bool) error {
|
||||
uw, err := openProxiedListUOW(ctx)
|
||||
if err != nil {
|
||||
return HandleError("%v", err)
|
||||
// proxiedStatsReporter hands back the guarded summary-statistics surface for
|
||||
// the proxied-server provider, through the provider's OWN capability accessor —
|
||||
// the same two-step proxiedCounter performs, and for the same reason: the
|
||||
// accessor is where each layer is added.
|
||||
//
|
||||
// This file used to hold a second copy of `bd status`: it opened a unit of
|
||||
// work, ran the statistics query, and — under --assigned — built the assignee
|
||||
// filter, ran the ready-work query and folded the five status counts itself,
|
||||
// beside a direct route doing the same three things again. All of that is
|
||||
// behind the role now, so the proxied route differs from the direct one by
|
||||
// which accessor it asks and nothing else.
|
||||
//
|
||||
// The role is asked for at the TOP of the command, before any work: this
|
||||
// command resolves no ids, so there is nothing to look up first and no
|
||||
// lookup-only provider to trip over.
|
||||
func proxiedStatsReporter() (issueops.StatsReporter, error) {
|
||||
if uowProvider == nil {
|
||||
return nil, errors.New("proxied-server UOW provider not initialized")
|
||||
}
|
||||
defer uw.Close(ctx)
|
||||
|
||||
stats, err := uw.IssueUseCase().GetStatistics(ctx)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
src, ok := uowProvider.(uow.StatsReporterSource)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("proxied-server provider %T does not offer the summary-statistics surface", uowProvider)
|
||||
}
|
||||
|
||||
if showAssigned {
|
||||
stats, err = proxiedAssignedStatistics(ctx, uw, actor)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("failed to get assigned statistics: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
var recentActivity *RecentActivitySummary
|
||||
if !noActivity {
|
||||
recentActivity = getGitActivity(24)
|
||||
}
|
||||
|
||||
return renderStatus(stats, recentActivity)
|
||||
}
|
||||
|
||||
func proxiedAssignedStatistics(ctx context.Context, uw uow.UnitOfWork, assignee string) (*types.Statistics, error) {
|
||||
assigneePtr := assignee
|
||||
page, err := uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{Assignee: &assigneePtr})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
readyCount := 0
|
||||
readyPage, err := uw.IssueUseCase().GetReadyWork(ctx, types.WorkFilter{Assignee: &assigneePtr})
|
||||
if err == nil {
|
||||
readyCount = len(readyPage.Items)
|
||||
}
|
||||
|
||||
return buildAssignedStats(page.Items, readyCount), nil
|
||||
return src.StatsReporter()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,50 +8,12 @@ import (
|
|||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
func TestBuildAssignedStats(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
issues []*types.Issue
|
||||
ready int
|
||||
total int
|
||||
open int
|
||||
inProgress int
|
||||
blocked int
|
||||
deferred int
|
||||
closed int
|
||||
}{
|
||||
{
|
||||
name: "counts every status and ready work",
|
||||
issues: []*types.Issue{
|
||||
{Status: types.StatusOpen},
|
||||
{Status: types.StatusInProgress},
|
||||
{Status: types.StatusBlocked},
|
||||
{Status: types.StatusDeferred},
|
||||
{Status: types.StatusClosed},
|
||||
},
|
||||
ready: 2, total: 5, open: 1, inProgress: 1, blocked: 1, deferred: 1, closed: 1,
|
||||
},
|
||||
{
|
||||
name: "empty input retains explicit zero counts",
|
||||
ready: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := buildAssignedStats(tt.issues, tt.ready)
|
||||
if got.TotalIssues != tt.total || got.OpenIssues != tt.open || got.InProgressIssues != tt.inProgress || got.DeferredIssues != tt.deferred || got.ClosedIssues != tt.closed {
|
||||
t.Errorf("buildAssignedStats() = %+v, want total=%d open=%d in_progress=%d deferred=%d closed=%d", got, tt.total, tt.open, tt.inProgress, tt.deferred, tt.closed)
|
||||
}
|
||||
if got.BlockedIssues == nil || *got.BlockedIssues != tt.blocked {
|
||||
t.Errorf("blocked issues = %v, want %d", got.BlockedIssues, tt.blocked)
|
||||
}
|
||||
if got.ReadyIssues == nil || *got.ReadyIssues != tt.ready {
|
||||
t.Errorf("ready issues = %v, want %d", got.ReadyIssues, tt.ready)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
// The assignee fold this command used to own moved to
|
||||
// internal/workapi.FoldStatsAssigneeSummary when `bd status` went behind
|
||||
// issueops.StatsReporter, and its test moved with it
|
||||
// (internal/workapi/stats_test.go). It is the definition of what
|
||||
// `bd status --assigned` means and both routes now read it from there, so a
|
||||
// copy of the test here would pin a function this package no longer has.
|
||||
|
||||
func TestRenderStatusJSON(t *testing.T) {
|
||||
t.Setenv("BD_JSON_ENVELOPE", "0")
|
||||
|
|
|
|||
|
|
@ -209,6 +209,22 @@ type SettingsPage struct {
|
|||
NextCursor *string `json:"next_cursor,omitempty"`
|
||||
}
|
||||
|
||||
// Statistics Workspace summary counts. Two of them are DEPENDENCY-AWARE and two are structurally always zero; both facts are stated on the properties themselves, because every number here is the same JSON type and nothing else on the wire distinguishes them.
|
||||
//
|
||||
// This is the struct `bd status --json` marshals under `summary`, pinned so the two surfaces are one compatibility domain.
|
||||
type Statistics = types.Statistics
|
||||
|
||||
// StatsResponse The same envelope `bd status --json` prints, minus one member: the CLI also carries `recent_activity`, which every shipped code path leaves absent, so it is not published here.
|
||||
type StatsResponse struct {
|
||||
// BlockedCountSkipped True when the summary came back without the blocked-set scan, which is exactly `summary.blocked_issues == null`. It is DERIVED from the answer rather than echoed from the request: `skip_blocked` is a hint, and a backend with no cheaper path answers with the full numbers and this flag false.
|
||||
BlockedCountSkipped bool `json:"blocked_count_skipped"`
|
||||
|
||||
// Summary Workspace summary counts. Two of them are DEPENDENCY-AWARE and two are structurally always zero; both facts are stated on the properties themselves, because every number here is the same JSON type and nothing else on the wire distinguishes them.
|
||||
//
|
||||
// This is the struct `bd status --json` marshals under `summary`, pinned so the two surfaces are one compatibility domain.
|
||||
Summary Statistics `json:"summary"`
|
||||
}
|
||||
|
||||
// IssueID defines model for IssueID.
|
||||
type IssueID = string
|
||||
|
||||
|
|
@ -358,5 +374,20 @@ type ListReadyWorkParams struct {
|
|||
// ListReadyWorkParamsSort defines parameters for ListReadyWork.
|
||||
type ListReadyWorkParamsSort string
|
||||
|
||||
// GetStatsParams defines parameters for GetStats.
|
||||
type GetStatsParams struct {
|
||||
// Assignee Answer for ONE ACTOR instead of the workspace. Used as written: no trimming, no case folding, no alias expansion. An empty value is a 400 — the workspace-wide question is asked by OMITTING the parameter, and an empty assignee would otherwise select the rows with no assignee and report them as one actor's workload.
|
||||
//
|
||||
// IT CHANGES FOUR DEFINITIONS AT ONCE, and they are named on the `Statistics` properties rather than here: the set widens to include the ephemeral tier, `blocked_issues` counts the `blocked` STATUS instead of the dependency flag, `ready_issues` becomes the real ready-work count instead of a subtraction, and `pinned_issues` is always 0. An actor with no rows is a summary of zeros, not a 404.
|
||||
Assignee *string `form:"assignee,omitempty" json:"assignee,omitempty"`
|
||||
|
||||
// SkipBlocked Ask for the answer WITHOUT the blocked-set scan, which is the expensive half of this query on a large workspace — the same request `bd status --no-blocked` makes.
|
||||
//
|
||||
// IT IS A HINT. When it is honored, `blocked_issues` and `ready_issues` are both null and `blocked_count_skipped` is true; when the backend has no cheaper path the full numbers come back and the flag is false. Nothing else in the summary changes either way, so a client that reads neither pointer cannot tell the difference.
|
||||
//
|
||||
// IGNORED when `assignee` is set: that answer computes both numbers by a route with no fast path, and it is not an error to ask.
|
||||
SkipBlocked *bool `form:"skip_blocked,omitempty" json:"skip_blocked,omitempty"`
|
||||
}
|
||||
|
||||
// ClaimIssueJSONRequestBody defines body for ClaimIssue for application/json ContentType.
|
||||
type ClaimIssueJSONRequestBody = ClaimRequest
|
||||
|
|
|
|||
|
|
@ -353,6 +353,7 @@ var (
|
|||
_ uow.IssueReaderSource = timedProvider{}
|
||||
_ uow.IssueClaimerSource = timedProvider{}
|
||||
_ uow.WorkspaceConfigSource = timedProvider{}
|
||||
_ uow.StatsReporterSource = timedProvider{}
|
||||
)
|
||||
|
||||
// IssueReader builds the reader OVER THIS WRAPPER rather than delegating to the
|
||||
|
|
@ -394,6 +395,14 @@ func (p timedProvider) WorkspaceConfig() (issueops.WorkspaceConfig, error) {
|
|||
return uow.NewWorkspaceConfig(p)
|
||||
}
|
||||
|
||||
// StatsReporter builds the summary role OVER THIS WRAPPER, for the third time
|
||||
// and for the same reason: a reporter bound to the wrapped provider would open
|
||||
// its units of work outside this request's measurement and the summary route
|
||||
// would log uow_ms=0.000 forever.
|
||||
func (p timedProvider) StatsReporter() (issueops.StatsReporter, error) {
|
||||
return uow.NewStatsReporter(p)
|
||||
}
|
||||
|
||||
func (p timedProvider) NewUOW(ctx context.Context) (uow.UnitOfWork, error) {
|
||||
start := time.Now()
|
||||
uw, err := p.inner.NewUOW(ctx)
|
||||
|
|
|
|||
|
|
@ -29,10 +29,12 @@ var (
|
|||
_ apigen.Dependency = types.Dependency{}
|
||||
_ apigen.Comment = types.Comment{}
|
||||
_ apigen.BondRef = types.BondRef{}
|
||||
_ apigen.Statistics = types.Statistics{}
|
||||
|
||||
// The envelopes carry the canonical types too — pinning the schema is not
|
||||
// enough if a page's items resolve to something else.
|
||||
_ []types.IssueWithCounts = apigen.ReadyPage{}.Items
|
||||
_ []types.IssueWithCounts = apigen.IssuesPage{}.Items
|
||||
_ types.Issue = apigen.ClaimResponse{}.Issue
|
||||
_ types.Statistics = apigen.StatsResponse{}.Summary
|
||||
)
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ import (
|
|||
// The vocabulary is a one-way door: renaming or removing a documented
|
||||
// status+code pair breaks the wire. Adding one does not, which is why clients
|
||||
// are told to default-branch on unknown codes within a status class. Keep it
|
||||
// at what the six v0 operations actually need.
|
||||
// at what the seven v0 operations actually need.
|
||||
type Code string
|
||||
|
||||
// The v0 code vocabulary. Every value here is documented in the spec, and
|
||||
|
|
@ -146,6 +146,7 @@ const (
|
|||
OpHealth = "health"
|
||||
OpGetContext = "getContext"
|
||||
OpListReadyWork = "listReadyWork"
|
||||
OpGetStats = "getStats"
|
||||
OpListIssues = "listIssues"
|
||||
OpGetIssue = "getIssue"
|
||||
OpClaimIssue = "claimIssue"
|
||||
|
|
@ -164,7 +165,7 @@ const (
|
|||
// refusal every decoder performs — and both are deliberately absent from every
|
||||
// row here. They are uniform rules, not per-operation behavior, and the spec
|
||||
// documents them once at the document level rather than repeating them on all
|
||||
// eight operations; these rows carry what an operation produces beyond them.
|
||||
// nine operations; these rows carry what an operation produces beyond them.
|
||||
// Keep the two documents in step: a row here and the document-level prose are
|
||||
// the only two places that carve-out exists.
|
||||
var operationCodes = map[string][]Code{
|
||||
|
|
@ -185,6 +186,11 @@ var operationCodes = map[string][]Code{
|
|||
// a key stored as the empty string are one answer on this surface, so the
|
||||
// only refusal a key can earn is the 400 that says it was not a key.
|
||||
OpGetSetting: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
|
||||
// The 400 here is this operation's own, not the document-level
|
||||
// unknown-parameter rule: a malformed `skip_blocked`, and the EMPTY
|
||||
// `assignee` the document refuses rather than answering with the rows that
|
||||
// have no assignee.
|
||||
OpGetStats: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
|
||||
OpClaimIssue: {
|
||||
CodeInvalidArgument, CodeNotFound, CodeAlreadyClaimed, CodeNotClaimable,
|
||||
CodeBusy, CodeDBUnavailable, CodeInternal,
|
||||
|
|
|
|||
|
|
@ -21,11 +21,12 @@ import (
|
|||
// store rather than a unit-of-work provider, served by handing Listen the roles
|
||||
// directly.
|
||||
//
|
||||
// The fakes below implement issueops.Reader, issueops.Claimer and
|
||||
// issueops.WorkspaceConfig and NOTHING else — deliberately not
|
||||
// uow.UnitOfWorkProvider, because "a backend that cannot produce a unit of work
|
||||
// is still servable" is the property this whole seam exists for. If any of them
|
||||
// ever grows a NewUOW method these tests stop proving it.
|
||||
// The fakes below implement issueops.Reader, issueops.Claimer,
|
||||
// issueops.WorkspaceConfig and issueops.StatsReporter and NOTHING else —
|
||||
// deliberately not uow.UnitOfWorkProvider, because "a backend that cannot
|
||||
// produce a unit of work is still servable" is the property this whole seam
|
||||
// exists for. If any of them ever grows a NewUOW method these tests stop
|
||||
// proving it.
|
||||
|
||||
type roleReader struct {
|
||||
page issueops.IssuePage
|
||||
|
|
@ -144,6 +145,72 @@ func (c *roleSettings) getRequests() []issueops.GetSettingRequest {
|
|||
return append([]issueops.GetSettingRequest(nil), c.gets...)
|
||||
}
|
||||
|
||||
type roleStats struct {
|
||||
summary types.Statistics
|
||||
err error
|
||||
|
||||
mu sync.Mutex
|
||||
stats []issueops.StatsRequest
|
||||
assignees []issueops.AssigneeStatsRequest
|
||||
}
|
||||
|
||||
func (s *roleStats) Stats(_ context.Context, req issueops.StatsRequest) (issueops.StatsResult, error) {
|
||||
s.mu.Lock()
|
||||
s.stats = append(s.stats, req)
|
||||
s.mu.Unlock()
|
||||
if s.err != nil {
|
||||
return issueops.StatsResult{}, s.err
|
||||
}
|
||||
return issueops.StatsResult{Summary: s.summary}, nil
|
||||
}
|
||||
|
||||
func (s *roleStats) AssigneeStats(_ context.Context, req issueops.AssigneeStatsRequest) (issueops.StatsResult, error) {
|
||||
s.mu.Lock()
|
||||
s.assignees = append(s.assignees, req)
|
||||
s.mu.Unlock()
|
||||
if s.err != nil {
|
||||
return issueops.StatsResult{}, s.err
|
||||
}
|
||||
return issueops.StatsResult{Summary: s.summary}, nil
|
||||
}
|
||||
|
||||
func (s *roleStats) statsRequests() []issueops.StatsRequest {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]issueops.StatsRequest(nil), s.stats...)
|
||||
}
|
||||
|
||||
func (s *roleStats) assigneeRequests() []issueops.AssigneeStatsRequest {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]issueops.AssigneeStatsRequest(nil), s.assignees...)
|
||||
}
|
||||
|
||||
// rolesConfig completes a store-shaped database source.
|
||||
//
|
||||
// Listen requires the WHOLE role set together (checkDatabaseSource), so a test
|
||||
// that exercises one operation still has to hand over the roles the other
|
||||
// operations reach. This fills the ones the caller left nil with inert fakes
|
||||
// and keeps the ones it set, so a test names only the role it is about.
|
||||
//
|
||||
// Not for TestListenRequiresExactlyOneDatabaseSource: that test's whole subject
|
||||
// is the PARTIAL set, so it builds its Configs by hand.
|
||||
func rolesConfig(cfg Config) Config {
|
||||
if cfg.Reader == nil {
|
||||
cfg.Reader = &roleReader{}
|
||||
}
|
||||
if cfg.Claimer == nil {
|
||||
cfg.Claimer = &roleClaimer{}
|
||||
}
|
||||
if cfg.Settings == nil {
|
||||
cfg.Settings = &roleSettings{}
|
||||
}
|
||||
if cfg.Stats == nil {
|
||||
cfg.Stats = &roleStats{}
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
// countedPage is the fixture both database sources answer with, so a body
|
||||
// difference between them can only come from the construction.
|
||||
func countedPage() []*types.IssueWithCounts {
|
||||
|
|
@ -176,22 +243,30 @@ func TestListenRequiresExactlyOneDatabaseSource(t *testing.T) {
|
|||
cfg: Config{Provider: &fakeProvider{}},
|
||||
},
|
||||
{
|
||||
name: "both roles together are a complete source",
|
||||
cfg: Config{Reader: &roleReader{}, Claimer: &roleClaimer{}, Settings: &roleSettings{}},
|
||||
name: "every role together is a complete source",
|
||||
cfg: Config{Reader: &roleReader{}, Claimer: &roleClaimer{}, Settings: &roleSettings{}, Stats: &roleStats{}},
|
||||
},
|
||||
{
|
||||
name: "a reader without a claimer",
|
||||
cfg: Config{Reader: &roleReader{}, Settings: &roleSettings{}},
|
||||
cfg: Config{Reader: &roleReader{}, Settings: &roleSettings{}, Stats: &roleStats{}},
|
||||
wantErr: "no database source",
|
||||
},
|
||||
{
|
||||
name: "a claimer without a reader",
|
||||
cfg: Config{Claimer: &roleClaimer{}, Settings: &roleSettings{}},
|
||||
cfg: Config{Claimer: &roleClaimer{}, Settings: &roleSettings{}, Stats: &roleStats{}},
|
||||
wantErr: "no database source",
|
||||
},
|
||||
{
|
||||
name: "the issue roles without the settings role",
|
||||
cfg: Config{Reader: &roleReader{}, Claimer: &roleClaimer{}},
|
||||
cfg: Config{Reader: &roleReader{}, Claimer: &roleClaimer{}, Stats: &roleStats{}},
|
||||
wantErr: "no database source",
|
||||
},
|
||||
{
|
||||
// The role set is all-or-nothing rather than a required pair plus
|
||||
// optional extras: a config missing the summary role binds and then
|
||||
// faults on one route, which is the same mistake in a new place.
|
||||
name: "the read and write roles without the summary role",
|
||||
cfg: Config{Reader: &roleReader{}, Claimer: &roleClaimer{}, Settings: &roleSettings{}},
|
||||
wantErr: "no database source",
|
||||
},
|
||||
{
|
||||
|
|
@ -206,7 +281,7 @@ func TestListenRequiresExactlyOneDatabaseSource(t *testing.T) {
|
|||
},
|
||||
{
|
||||
name: "a provider and every role",
|
||||
cfg: Config{Provider: &fakeProvider{}, Reader: &roleReader{}, Claimer: &roleClaimer{}, Settings: &roleSettings{}},
|
||||
cfg: Config{Provider: &fakeProvider{}, Reader: &roleReader{}, Claimer: &roleClaimer{}, Settings: &roleSettings{}, Stats: &roleStats{}},
|
||||
wantErr: "exactly one database source",
|
||||
},
|
||||
} {
|
||||
|
|
@ -249,6 +324,7 @@ func TestConfiguredRolesServeTheSameReadyBytesAsAProvider(t *testing.T) {
|
|||
Reader: &roleReader{page: issueops.IssuePage{Items: items}},
|
||||
Claimer: &roleClaimer{},
|
||||
Settings: &roleSettings{},
|
||||
Stats: &roleStats{},
|
||||
})
|
||||
|
||||
for _, path := range []string{"/v0/beads/ready", "/v0/beads/issues"} {
|
||||
|
|
@ -269,6 +345,7 @@ func TestConfiguredRolesServeTheSameReadyBytesAsAProvider(t *testing.T) {
|
|||
}
|
||||
|
||||
// TestConfiguredRolesAnswerEveryDatabaseRoute drives all six
|
||||
// TestConfiguredRolesAnswerEveryDatabaseRoute drives all five
|
||||
// database-touching operations against a store-shaped source, which is the
|
||||
// whole point: none of them can reach a unit of work here, because there is no
|
||||
// provider to open one.
|
||||
|
|
@ -283,7 +360,9 @@ func TestConfiguredRolesAnswerEveryDatabaseRoute(t *testing.T) {
|
|||
value: "awaiting_review:active",
|
||||
settings: map[string]string{"status.custom": "awaiting_review:active", "notion.token": "secret-value"},
|
||||
}
|
||||
ts := newTestServer(t, Config{Reader: reader, Claimer: claimer, Settings: settings})
|
||||
blocked := 2
|
||||
reporter := &roleStats{summary: types.Statistics{TotalIssues: 7, OpenIssues: 5, BlockedIssues: &blocked}}
|
||||
ts := newTestServer(t, Config{Reader: reader, Claimer: claimer, Settings: settings, Stats: reporter})
|
||||
|
||||
t.Run("ready", func(t *testing.T) {
|
||||
resp := ts.get(t, "/v0/beads/ready?sort=oldest")
|
||||
|
|
@ -396,6 +475,43 @@ func TestConfiguredRolesAnswerEveryDatabaseRoute(t *testing.T) {
|
|||
t.Errorf("get requests = %+v, want one for status.custom", reqs)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("stats", func(t *testing.T) {
|
||||
resp := ts.get(t, "/v0/beads/stats?skip_blocked=true")
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
body := decodeBody(t, resp)
|
||||
summary, _ := body["summary"].(map[string]any)
|
||||
if summary["total_issues"] != float64(7) {
|
||||
t.Errorf("summary = %v, want the counts the role reported", summary)
|
||||
}
|
||||
// The role answered with a populated blocked count, so the hint was not
|
||||
// taken and the flag says so — derived from the answer, not echoed from
|
||||
// the request that asked for the fast path.
|
||||
if body["blocked_count_skipped"] != false {
|
||||
t.Errorf("blocked_count_skipped = %v, want false beside a populated blocked_issues", body["blocked_count_skipped"])
|
||||
}
|
||||
if reqs := reporter.statsRequests(); len(reqs) != 1 || !reqs[0].SkipBlocked {
|
||||
t.Errorf("stats requests = %+v, want one carrying SkipBlocked", reqs)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("stats for one assignee", func(t *testing.T) {
|
||||
resp := ts.get(t, "/v0/beads/stats?assignee=alice&skip_blocked=true")
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
// The assignee-scoped method, with the hint dropped rather than
|
||||
// forwarded: that request type has no such field.
|
||||
reqs := reporter.assigneeRequests()
|
||||
if len(reqs) != 1 || reqs[0].Assignee != "alice" {
|
||||
t.Errorf("assignee requests = %+v, want one for alice", reqs)
|
||||
}
|
||||
if got := reporter.statsRequests(); len(got) != 1 {
|
||||
t.Errorf("the workspace-wide method was called %d times, want the 1 from the subtest above: an assignee asks the other question", len(got))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestConfiguredRolesKeepTheDocumentedRefusals: the error vocabulary belongs to
|
||||
|
|
@ -408,6 +524,7 @@ func TestConfiguredRolesKeepTheDocumentedRefusals(t *testing.T) {
|
|||
Reader: &roleReader{err: fmt.Errorf("get bd-404: %w", storage.ErrNotFound)},
|
||||
Claimer: &roleClaimer{},
|
||||
Settings: &roleSettings{},
|
||||
Stats: &roleStats{},
|
||||
})
|
||||
resp := ts.get(t, "/v0/beads/issues/bd-404")
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
|
|
@ -426,6 +543,7 @@ func TestConfiguredRolesKeepTheDocumentedRefusals(t *testing.T) {
|
|||
Reader: &roleReader{err: errors.New("invalid status bogus")},
|
||||
Claimer: &roleClaimer{},
|
||||
Settings: &roleSettings{},
|
||||
Stats: &roleStats{},
|
||||
})
|
||||
resp := ts.get(t, "/v0/beads/issues?status=bogus")
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
|
|
@ -440,6 +558,7 @@ func TestConfiguredRolesKeepTheDocumentedRefusals(t *testing.T) {
|
|||
t.Run("a foreign holder is 409 with its state", func(t *testing.T) {
|
||||
ts := newTestServer(t, Config{
|
||||
Reader: &roleReader{},
|
||||
Stats: &roleStats{},
|
||||
Claimer: &roleClaimer{err: &issueops.ClaimConflictError{
|
||||
IssueID: "bd-1",
|
||||
Assignee: "bob",
|
||||
|
|
@ -466,6 +585,7 @@ func TestConfiguredRolesKeepTheDocumentedRefusals(t *testing.T) {
|
|||
Reader: &roleReader{err: errors.New("backend is unreachable")},
|
||||
Claimer: &roleClaimer{},
|
||||
Settings: &roleSettings{},
|
||||
Stats: &roleStats{},
|
||||
})
|
||||
resp := ts.get(t, "/v0/beads/ready")
|
||||
if resp.StatusCode != http.StatusInternalServerError {
|
||||
|
|
@ -495,7 +615,7 @@ func TestStartupNamesTheDatabaseSource(t *testing.T) {
|
|||
})
|
||||
|
||||
t.Run("roles", func(t *testing.T) {
|
||||
ts := newTestServer(t, Config{Reader: &roleReader{}, Claimer: &roleClaimer{}, Settings: &roleSettings{}})
|
||||
ts := newTestServer(t, rolesConfig(Config{}))
|
||||
startup := findLogLine(t, ts.stderr.String(), "event=startup")
|
||||
if !strings.Contains(startup, "db=roles") {
|
||||
t.Errorf("startup line does not name the database source:\n%s", startup)
|
||||
|
|
@ -516,7 +636,7 @@ func TestStartupNamesTheDatabaseSource(t *testing.T) {
|
|||
// number really is zero, and it is zero because nothing on this path opens a
|
||||
// unit of work — not because the timing wrapper was dropped.
|
||||
func TestARolesRequestReportsNoUnitOfWorkTime(t *testing.T) {
|
||||
ts := newTestServer(t, Config{Reader: &roleReader{}, Claimer: &roleClaimer{}, Settings: &roleSettings{}})
|
||||
ts := newTestServer(t, rolesConfig(Config{}))
|
||||
|
||||
if resp := ts.get(t, "/v0/beads/ready"); resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", resp.StatusCode)
|
||||
|
|
@ -531,7 +651,7 @@ func TestARolesRequestReportsNoUnitOfWorkTime(t *testing.T) {
|
|||
// of work, and a roles-backed server has nothing to open one from. An error is
|
||||
// the answer; a nil dereference inside a handler is not.
|
||||
func TestWithUOWRefusesWithoutAProvider(t *testing.T) {
|
||||
ts := newTestServer(t, Config{Reader: &roleReader{}, Claimer: &roleClaimer{}, Settings: &roleSettings{}})
|
||||
ts := newTestServer(t, rolesConfig(Config{}))
|
||||
|
||||
ran := false
|
||||
err := ts.WithUOW(context.Background(), &reqInfo{}, func(uow.UnitOfWork) error {
|
||||
|
|
@ -562,11 +682,12 @@ func TestARoleThatAnswersWithNothingIsNotDereferenced(t *testing.T) {
|
|||
// document states one not-found body, and a client must not be able to
|
||||
// tell a broken role from an absent issue.
|
||||
t.Run("a reader with no detail view is the documented miss", func(t *testing.T) {
|
||||
silent := newTestServer(t, Config{Reader: &roleReader{}, Claimer: &roleClaimer{}, Settings: &roleSettings{}})
|
||||
silent := newTestServer(t, rolesConfig(Config{}))
|
||||
missed := newTestServer(t, Config{
|
||||
Reader: &roleReader{err: fmt.Errorf("get bd-1: %w", storage.ErrNotFound)},
|
||||
Claimer: &roleClaimer{},
|
||||
Settings: &roleSettings{},
|
||||
Stats: &roleStats{},
|
||||
})
|
||||
|
||||
got := silent.get(t, "/v0/beads/issues/bd-1")
|
||||
|
|
@ -594,6 +715,7 @@ func TestARoleThatAnswersWithNothingIsNotDereferenced(t *testing.T) {
|
|||
Reader: &roleReader{},
|
||||
Claimer: &roleClaimer{result: issueops.ClaimResult{Changed: true}},
|
||||
Settings: &roleSettings{},
|
||||
Stats: &roleStats{},
|
||||
})
|
||||
|
||||
resp := ts.claim(t, claimPath, `{"actor":"alice"}`)
|
||||
|
|
@ -667,6 +789,7 @@ func TestListenRefusesARoleThatFiresTheWorkspaceHooks(t *testing.T) {
|
|||
Reader: &roleReader{},
|
||||
Claimer: cl,
|
||||
Settings: &roleSettings{},
|
||||
Stats: &roleStats{},
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -76,6 +76,17 @@ var routeTable = []route{
|
|||
implemented: true,
|
||||
handler: (*Server).handleReady,
|
||||
},
|
||||
{
|
||||
op: OpGetStats,
|
||||
method: http.MethodGet,
|
||||
// `stats`, not `status`: on an HTTP surface `status` reads as the
|
||||
// server's own condition, which is /healthz. This one answers about the
|
||||
// workspace and takes a database slot to do it.
|
||||
pattern: "/v0/beads/stats",
|
||||
capability: "stats.get",
|
||||
implemented: true,
|
||||
handler: (*Server).handleStats,
|
||||
},
|
||||
{
|
||||
op: OpListIssues,
|
||||
method: http.MethodGet,
|
||||
|
|
|
|||
|
|
@ -120,14 +120,21 @@ type Config struct {
|
|||
// Provider is where every database-touching handler opens its one unit of
|
||||
// work per request.
|
||||
Provider uow.UnitOfWorkProvider
|
||||
// Reader and Claimer are the issue roles this server answers from, for a
|
||||
// backend whose facade is a STORE rather than a unit-of-work provider.
|
||||
// Reader, Claimer, Settings and Stats are the roles this server answers
|
||||
// from, for a backend whose facade is a STORE rather than a unit-of-work
|
||||
// provider. sourceRoles is the authoritative list.
|
||||
//
|
||||
// Set all three together, and only when Provider is nil: they are the
|
||||
// other complete database source, not an override of one. Listen refuses
|
||||
// every other combination, including a half-set set — a reader without a
|
||||
// claimer would bind, answer every read, and fail the one issue write on
|
||||
// this surface with a nil dereference inside a handler.
|
||||
// Set them together, and only when Provider is nil: they are the other
|
||||
// complete database source, not an override of one. Listen refuses every
|
||||
// other combination, including a PARTIAL set — a reader without a claimer
|
||||
// would bind, answer every read, and fail the one write on this surface with
|
||||
// a nil dereference inside a handler, and the same is true of every
|
||||
// operation whose role is missing.
|
||||
//
|
||||
// The set grows as operations do: each role a new operation reaches becomes
|
||||
// another field here and another one this source must carry, because a
|
||||
// database source that answers some operations and faults on others is not
|
||||
// a source.
|
||||
//
|
||||
// A caller with a store takes them off the store's own accessors, and WHICH
|
||||
// store value it takes them off is the whole question. Every decorator a
|
||||
|
|
@ -145,7 +152,8 @@ type Config struct {
|
|||
// rd, err := src.IssueReader()
|
||||
// cl, err := src.IssueClaimer()
|
||||
// wc, err := src.WorkspaceConfig()
|
||||
// httpapi.Listen(httpapi.Config{Reader: rd, Claimer: cl, Settings: wc, ...})
|
||||
// st, err := src.StatsReporter()
|
||||
// httpapi.Listen(httpapi.Config{Reader: rd, Claimer: cl, Settings: wc, Stats: st, ...})
|
||||
//
|
||||
// Listen refuses a hook-firing role rather than trusting the paragraph
|
||||
// above — see checkDatabaseSource.
|
||||
|
|
@ -165,14 +173,15 @@ type Config struct {
|
|||
// (see Server.reader) — and a role reached this way opens none through this
|
||||
// server, so a rebuild would buy nothing.
|
||||
//
|
||||
// Settings joins them for the same reason Claimer does, and the "set them
|
||||
// together" rule covers all three: this surface publishes two settings
|
||||
// operations, so a Reader and a Claimer without a Settings would bind,
|
||||
// answer every issue route, and fail both config routes with a nil
|
||||
// dereference inside a handler.
|
||||
// Settings and Stats join them for the same reason Claimer does, and the
|
||||
// "set them together" rule covers all of them: this surface publishes two
|
||||
// settings operations and a summary operation, so a Reader and a Claimer
|
||||
// without them would bind, answer every issue route, and fail those routes
|
||||
// with a nil dereference inside a handler.
|
||||
Reader issueops.Reader
|
||||
Claimer issueops.Claimer
|
||||
Settings issueops.WorkspaceConfig
|
||||
Stats issueops.StatsReporter
|
||||
// Workspace is the startup snapshot GET /v0/beads/context answers from.
|
||||
// Only the allowlisted fields are ever serialized — see contextResponse,
|
||||
// which names the whole set and the reasons for the exclusions.
|
||||
|
|
@ -196,13 +205,14 @@ type Server struct {
|
|||
cfg Config
|
||||
provider uow.UnitOfWorkProvider
|
||||
|
||||
// issueReader and issueClaimer are the configured roles, set exactly when
|
||||
// provider is nil. They are what reader() and claimer() hand back on the
|
||||
// store-shaped source; the names differ from those methods because a struct
|
||||
// cannot carry both.
|
||||
// These are the configured roles, set exactly when provider is nil. They
|
||||
// are what reader(), claimer(), workspaceConfig() and statsReporter() hand
|
||||
// back on the store-shaped source; some names differ from those methods
|
||||
// because a struct cannot carry both.
|
||||
issueReader issueops.Reader
|
||||
issueClaimer issueops.Claimer
|
||||
settings issueops.WorkspaceConfig
|
||||
issueStats issueops.StatsReporter
|
||||
|
||||
listener net.Listener
|
||||
http *http.Server
|
||||
|
|
@ -302,6 +312,7 @@ func Listen(cfg Config) (*Server, error) {
|
|||
issueReader: cfg.Reader,
|
||||
issueClaimer: cfg.Claimer,
|
||||
settings: cfg.Settings,
|
||||
issueStats: cfg.Stats,
|
||||
|
||||
sem: make(chan struct{}, maxInflight),
|
||||
semTimeout: semAcquireTimeout,
|
||||
|
|
@ -355,11 +366,14 @@ func Listen(cfg Config) (*Server, error) {
|
|||
// checkDatabaseSource enforces exactly one complete database source.
|
||||
//
|
||||
// There are two, and a Config carries one or the other: a unit-of-work
|
||||
// provider, or the three roles this surface answers from. A HALF-SET set is
|
||||
// refused with the same message as none at all, because it is the same mistake
|
||||
// and the failure it would otherwise produce is the worst shape available — a
|
||||
// reader without a claimer binds, answers every read, and fails the one issue
|
||||
// write on this surface with a nil dereference in a handler on a live server.
|
||||
// provider, or the roles this surface answers from (sourceRoles). A PARTIAL
|
||||
// set is refused with the same message as none at all, because it is the same
|
||||
// mistake and the failure it would otherwise produce is the worst shape
|
||||
// available — a reader without a claimer binds, answers every read, and fails
|
||||
// the one issue write on this surface with a nil dereference in a handler on a
|
||||
// live server. A missing settings or summary role is the same failure on a
|
||||
// different route, which is why the set is all-or-nothing rather than a
|
||||
// required pair plus optional extras.
|
||||
//
|
||||
// Both together is refused rather than resolved by precedence: a caller that
|
||||
// set both holds two different opinions about where this server reads from, and
|
||||
|
|
@ -375,13 +389,43 @@ func Listen(cfg Config) (*Server, error) {
|
|||
// at Listen is the difference between a startup error naming the store to take
|
||||
// roles from and a server that has been quietly running a user's subprocess per
|
||||
// claim since it booted.
|
||||
// sourceRoles is the store-shaped source's roles in ONE place, so the three
|
||||
// questions checkDatabaseSource asks — is any set, is any missing, does any
|
||||
// fire hooks — cannot drift apart from each other as the set grows. An
|
||||
// operation that reaches a role this source does not yet carry adds a line
|
||||
// here and a line to roleSourceNames, and nothing else in this file.
|
||||
//
|
||||
// A role is compared against nil as an INTERFACE, which is what the caller
|
||||
// actually sets; a typed nil stored in one of these fields is a value as far
|
||||
// as this check is concerned, exactly as it was when the check was a hand-
|
||||
// written boolean per role.
|
||||
func sourceRoles(cfg Config) []any {
|
||||
return []any{cfg.Reader, cfg.Claimer, cfg.Settings, cfg.Stats}
|
||||
}
|
||||
|
||||
// roleSourceNames spells sourceRoles for the refusal message, in the same
|
||||
// order, so a caller reading the error learns the whole set it must pass.
|
||||
const roleSourceNames = "Reader, Claimer, Settings and Stats"
|
||||
|
||||
func anyRoleSet(cfg Config) bool {
|
||||
return slices.ContainsFunc(sourceRoles(cfg), func(r any) bool { return r != nil })
|
||||
}
|
||||
|
||||
func everyRoleSet(cfg Config) bool {
|
||||
return !slices.Contains(sourceRoles(cfg), nil)
|
||||
}
|
||||
|
||||
func anyRoleFiresHooks(cfg Config) bool {
|
||||
return slices.ContainsFunc(sourceRoles(cfg), storage.RoleFiresHooks)
|
||||
}
|
||||
|
||||
func checkDatabaseSource(cfg Config) error {
|
||||
switch {
|
||||
case cfg.Provider != nil && (cfg.Reader != nil || cfg.Claimer != nil || cfg.Settings != nil):
|
||||
case cfg.Provider != nil && anyRoleSet(cfg):
|
||||
return errors.New("httpapi: both a unit-of-work provider and issue roles were set; pass exactly one database source")
|
||||
case cfg.Provider == nil && (cfg.Reader == nil || cfg.Claimer == nil || cfg.Settings == nil):
|
||||
return errors.New("httpapi: no database source: set Provider, or Reader, Claimer and Settings together")
|
||||
case storage.RoleFiresHooks(cfg.Reader) || storage.RoleFiresHooks(cfg.Claimer) || storage.RoleFiresHooks(cfg.Settings):
|
||||
case cfg.Provider == nil && !everyRoleSet(cfg):
|
||||
return errors.New("httpapi: no database source: set Provider, or " + roleSourceNames + " together")
|
||||
case anyRoleFiresHooks(cfg):
|
||||
return errors.New("httpapi: a configured role fires this workspace's hooks; " +
|
||||
"this server does not run hooks, so take the roles from the store beneath the hook decorator " +
|
||||
"((*storage.HookFiringStore).Unwrap)")
|
||||
|
|
@ -488,6 +532,26 @@ func (s *Server) reader(r *http.Request) (issueops.Reader, error) {
|
|||
return checkedReader{inner: rd}, nil
|
||||
}
|
||||
|
||||
// statsReporter returns the guarded summary-statistics surface for one request.
|
||||
//
|
||||
// It is the third of the same shape reader() and claimer() have, for the same
|
||||
// reasons: the configured role on the roles source, one built per request on the
|
||||
// provider source so its units of work land in THIS request's uow_ms, and the
|
||||
// source held by INTERFACE so uow.StatsReporterSource is load-bearing rather
|
||||
// than decorative.
|
||||
//
|
||||
// There is no checked wrapper around it, and that is a property of the role
|
||||
// rather than an omission: issueops.StatsResult carries a VALUE, so there is no
|
||||
// nil-with-nil-error answer for a handler to dereference. checkedReader exists
|
||||
// because Reader.Get hands back a pointer.
|
||||
func (s *Server) statsReporter(r *http.Request) (issueops.StatsReporter, error) {
|
||||
if s.provider == nil {
|
||||
return s.issueStats, nil
|
||||
}
|
||||
var src uow.StatsReporterSource = timedProvider{inner: s.provider, rec: requestInfo(r.Context())}
|
||||
return src.StatsReporter()
|
||||
}
|
||||
|
||||
// claimer returns the guarded atomic-claim surface for one request.
|
||||
//
|
||||
// It is the write-side twin of reader above, for all the same reasons: the
|
||||
|
|
|
|||
|
|
@ -567,7 +567,7 @@ func TestCapabilitiesAdvertiseEveryImplementedOperation(t *testing.T) {
|
|||
for _, c := range caps {
|
||||
got = append(got, c.(string))
|
||||
}
|
||||
want := []string{"config.get", "config.list", "issues.claim", "issues.get", "issues.list", "ready.list"}
|
||||
want := []string{"config.get", "config.list", "issues.claim", "issues.get", "issues.list", "ready.list", "stats.get"}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Errorf("capabilities = %v, want %v", got, want)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -61,7 +61,7 @@ info:
|
|||
|
||||
|
||||
Both are uniform rules, reachable on EVERY route including `GET /healthz`,
|
||||
and are stated here instead of being repeated on all eight operations. The
|
||||
and are stated here instead of being repeated on all nine operations. The
|
||||
per-operation `responses` below therefore list what an operation produces
|
||||
BEYOND these two: a generated client must treat `400 invalid_argument` as
|
||||
possible everywhere, including on the operations whose documented statuses
|
||||
|
|
@ -98,12 +98,13 @@ info:
|
|||
|
||||
|
||||
`Issue`, `IssueWithCounts`, `IssueDetails`,
|
||||
`IssueWithDependencyMetadata`, `Dependency`, `Comment` and `BondRef` 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 seven, fails CI otherwise. A
|
||||
`IssueWithDependencyMetadata`, `Dependency`, `Comment`, `BondRef` and
|
||||
`Statistics` 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 eight, fails
|
||||
CI otherwise. A
|
||||
breaking change to those shapes requires cutting `/v1`, not editing `/v0`.
|
||||
|
||||
|
||||
|
|
@ -417,6 +418,85 @@ paths:
|
|||
'503':
|
||||
$ref: '#/components/responses/Unavailable'
|
||||
|
||||
/v0/beads/stats:
|
||||
get:
|
||||
operationId: getStats
|
||||
summary: Workspace summary statistics
|
||||
description: >-
|
||||
The counts `bd status` prints and its `bd stats` alias reprints: rows by
|
||||
status across the durable plane, plus the two DEPENDENCY-AWARE numbers —
|
||||
the blocked count and the readiness derived from it — that make this a
|
||||
different question from a filtered count.
|
||||
|
||||
|
||||
It is `stats` rather than `status` in the path deliberately. `status`
|
||||
on an HTTP surface reads as the SERVER's condition, which is `/healthz`;
|
||||
this operation answers about the WORKSPACE and touches the database to
|
||||
do it.
|
||||
|
||||
|
||||
THE WISP TIER IS NOT INCLUDED in the workspace-wide answer, so a
|
||||
workspace whose work lives in ephemeral rows reports zeros here.
|
||||
Supplying `assignee` changes that, along with three other definitions —
|
||||
see the parameter.
|
||||
|
||||
|
||||
THERE IS NO PREDICATE and there will not be one. A count of a set the
|
||||
caller describes is a different question with a different answer shape;
|
||||
this operation is the summary or it is nothing.
|
||||
parameters:
|
||||
- name: assignee
|
||||
in: query
|
||||
description: >-
|
||||
Answer for ONE ACTOR instead of the workspace. Used as written: no
|
||||
trimming, no case folding, no alias expansion. An empty value is a
|
||||
400 — the workspace-wide question is asked by OMITTING the
|
||||
parameter, and an empty assignee would otherwise select the rows
|
||||
with no assignee and report them as one actor's workload.
|
||||
|
||||
|
||||
IT CHANGES FOUR DEFINITIONS AT ONCE, and they are named on the
|
||||
`Statistics` properties rather than here: the set widens to include
|
||||
the ephemeral tier, `blocked_issues` counts the `blocked` STATUS
|
||||
instead of the dependency flag, `ready_issues` becomes the real
|
||||
ready-work count instead of a subtraction, and `pinned_issues` is
|
||||
always 0. An actor with no rows is a summary of zeros, not a 404.
|
||||
schema:
|
||||
type: string
|
||||
- name: skip_blocked
|
||||
in: query
|
||||
description: >-
|
||||
Ask for the answer WITHOUT the blocked-set scan, which is the
|
||||
expensive half of this query on a large workspace — the same request
|
||||
`bd status --no-blocked` makes.
|
||||
|
||||
|
||||
IT IS A HINT. When it is honored, `blocked_issues` and
|
||||
`ready_issues` are both null and `blocked_count_skipped` is true;
|
||||
when the backend has no cheaper path the full numbers come back and
|
||||
the flag is false. Nothing else in the summary changes either way,
|
||||
so a client that reads neither pointer cannot tell the difference.
|
||||
|
||||
|
||||
IGNORED when `assignee` is set: that answer computes both numbers by
|
||||
a route with no fast path, and it is not an error to ask.
|
||||
schema:
|
||||
type: boolean
|
||||
default: false
|
||||
responses:
|
||||
'200':
|
||||
description: The workspace summary.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/StatsResponse'
|
||||
'400':
|
||||
$ref: '#/components/responses/InvalidArgument'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalError'
|
||||
'503':
|
||||
$ref: '#/components/responses/Unavailable'
|
||||
|
||||
/v0/beads/issues:
|
||||
get:
|
||||
operationId: listIssues
|
||||
|
|
@ -892,7 +972,7 @@ components:
|
|||
# ---------------------------------------------------------------------
|
||||
# Pinned schemas.
|
||||
#
|
||||
# Each of the seven below is `x-go-type`-pinned to the canonical Go struct,
|
||||
# Each of the eight 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.
|
||||
|
|
@ -1435,6 +1515,96 @@ components:
|
|||
bond_type: { type: string }
|
||||
bond_point: { type: string }
|
||||
|
||||
Statistics:
|
||||
type: object
|
||||
description: >-
|
||||
Workspace summary counts. Two of them are DEPENDENCY-AWARE and two are
|
||||
structurally always zero; both facts are stated on the properties
|
||||
themselves, because every number here is the same JSON type and nothing
|
||||
else on the wire distinguishes them.
|
||||
|
||||
|
||||
This is the struct `bd status --json` marshals under `summary`, pinned
|
||||
so the two surfaces are one compatibility domain.
|
||||
x-go-type: types.Statistics
|
||||
x-go-type-import:
|
||||
name: types
|
||||
path: github.com/steveyegge/beads/internal/types
|
||||
required:
|
||||
- total_issues
|
||||
- open_issues
|
||||
- in_progress_issues
|
||||
- closed_issues
|
||||
- blocked_issues
|
||||
- deferred_issues
|
||||
- ready_issues
|
||||
- pinned_issues
|
||||
- epics_eligible_for_closure
|
||||
- average_lead_time_hours
|
||||
properties:
|
||||
total_issues:
|
||||
type: integer
|
||||
description: >-
|
||||
Every row in the workspace-wide answer's scan, INCLUDING closed and
|
||||
pinned ones. The status counts below do not sum to it: a row whose
|
||||
status is none of the four falls into no bucket, and `pinned_issues`
|
||||
counts a flag that overlaps all of them.
|
||||
open_issues:
|
||||
type: integer
|
||||
in_progress_issues:
|
||||
type: integer
|
||||
closed_issues:
|
||||
type: integer
|
||||
deferred_issues:
|
||||
type: integer
|
||||
blocked_issues:
|
||||
type: integer
|
||||
nullable: true
|
||||
description: >-
|
||||
Rows the dependency graph blocks — the transitive is_blocked flag,
|
||||
NOT the count of rows whose status is `blocked`. An open row with an
|
||||
unfinished blocker is counted here and its status is still `open`.
|
||||
|
||||
|
||||
NULL when `skip_blocked` was honored, always together with
|
||||
`ready_issues`. The two are nil together or populated together;
|
||||
there is no state in which one is knowable and the other is not.
|
||||
|
||||
|
||||
When `assignee` is set this is a different number: the count of that
|
||||
actor's rows whose STATUS is `blocked`, and never null.
|
||||
ready_issues:
|
||||
type: integer
|
||||
nullable: true
|
||||
description: >-
|
||||
ARITHMETIC, not a query: `open_issues` minus `blocked_issues`,
|
||||
clamped at zero. It is NOT the cardinality of `GET /v0/beads/ready`,
|
||||
which applies type exclusions, the deferral window and a limit that
|
||||
none of this touches.
|
||||
|
||||
|
||||
NULL under the same conditions as `blocked_issues`.
|
||||
|
||||
|
||||
When `assignee` is set this is the real ready-work count for that
|
||||
actor, and never null.
|
||||
pinned_issues:
|
||||
type: integer
|
||||
description: >-
|
||||
Rows carrying the pinned flag, overlapping every status bucket.
|
||||
Always 0 when `assignee` is set: that answer tallies the five
|
||||
statuses and nothing else.
|
||||
epics_eligible_for_closure:
|
||||
type: integer
|
||||
description: >-
|
||||
ALWAYS 0. No implementation computes it, on any backend or either
|
||||
surface. It is documented rather than dropped because this schema is
|
||||
pinned to the struct both surfaces marshal, and a caller reading a 0
|
||||
here is reading an absent computation rather than an answer.
|
||||
average_lead_time_hours:
|
||||
type: number
|
||||
description: ALWAYS 0, for the reason above.
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Envelope schemas. These have no canonical Go type behind them: they are
|
||||
# new wire surface, generated normally, and the generated type is the only
|
||||
|
|
@ -1623,6 +1793,24 @@ components:
|
|||
type: string
|
||||
description: >-
|
||||
Present if and only if `has_more` is true, which is never in v0.
|
||||
StatsResponse:
|
||||
type: object
|
||||
required: [summary, blocked_count_skipped]
|
||||
description: >-
|
||||
The same envelope `bd status --json` prints, minus one member: the CLI
|
||||
also carries `recent_activity`, which every shipped code path leaves
|
||||
absent, so it is not published here.
|
||||
properties:
|
||||
summary:
|
||||
$ref: '#/components/schemas/Statistics'
|
||||
blocked_count_skipped:
|
||||
type: boolean
|
||||
description: >-
|
||||
True when the summary came back without the blocked-set scan, which
|
||||
is exactly `summary.blocked_issues == null`. It is DERIVED from the
|
||||
answer rather than echoed from the request: `skip_blocked` is a
|
||||
hint, and a backend with no cheaper path answers with the full
|
||||
numbers and this flag false.
|
||||
|
||||
ClaimRequest:
|
||||
type: object
|
||||
|
|
|
|||
77
internal/httpapi/stats.go
Normal file
77
internal/httpapi/stats.go
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/steveyegge/beads/internal/httpapi/apigen"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// The summary operation. It decodes two parameters, hands the whole request to
|
||||
// the summary role, and shapes the answer onto the wire.
|
||||
//
|
||||
// WHAT IS NOT HERE IS THE POINT, exactly as in reads.go. No filter is built,
|
||||
// no assignee predicate is assembled, no ready-work query is issued and no
|
||||
// status fold is performed: all of that is inside issueops.StatsReporter's
|
||||
// implementation, which `bd status` reaches through the same accessor on both
|
||||
// of its routes. The fold in particular is the thing worth keeping out of a
|
||||
// handler — it is where "your work" is DEFINED, and a second copy of it here
|
||||
// would be a second definition that nothing compares against the first.
|
||||
//
|
||||
// WHICH METHOD IS TRANSPORT'S CALL, and it is the only decision this file
|
||||
// makes about meaning: an absent `assignee` is the workspace-wide question, a
|
||||
// present one is the actor question, and an EMPTY one is neither, so it is
|
||||
// refused here rather than passed down. The role would refuse it too
|
||||
// (ErrValidation), but a 400 that names the parameter is what a client can act
|
||||
// on, and the document says the workspace-wide question is asked by omitting
|
||||
// the parameter rather than by emptying it.
|
||||
|
||||
// handleStats answers GET /v0/beads/stats.
|
||||
func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) {
|
||||
q := newQuery(r.URL.Query())
|
||||
|
||||
assignee := q.str("assignee")
|
||||
skipBlocked := q.boolean("skip_blocked")
|
||||
|
||||
// Supplied-but-empty is distinguishable from absent only at the raw values:
|
||||
// q.str answers "" for both. The refusal goes through the query's own
|
||||
// first-refusal slot so a request that is also malformed elsewhere reports
|
||||
// one parameter rather than depending on read order.
|
||||
if assignee == "" && r.URL.Query().Has("assignee") {
|
||||
q.invalid("assignee", "an assignee must not be empty; omit the parameter for the workspace-wide summary")
|
||||
}
|
||||
|
||||
if !s.acceptQuery(w, r, q) {
|
||||
return
|
||||
}
|
||||
|
||||
reporter, err := s.statsReporter(r)
|
||||
if err != nil {
|
||||
s.failErr(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var result issueops.StatsResult
|
||||
if assignee != "" {
|
||||
// skip_blocked is not forwarded, and there is nothing to forward it
|
||||
// to: AssigneeStatsRequest has no such field, because that answer
|
||||
// computes both numbers by a route with no fast path. The document
|
||||
// says the parameter is ignored here; this is where it is ignored.
|
||||
result, err = reporter.AssigneeStats(r.Context(), issueops.AssigneeStatsRequest{Assignee: assignee})
|
||||
} else {
|
||||
result, err = reporter.Stats(r.Context(), issueops.StatsRequest{SkipBlocked: skipBlocked})
|
||||
}
|
||||
if err != nil {
|
||||
s.failErr(w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, apigen.StatsResponse{
|
||||
Summary: result.Summary,
|
||||
// DERIVED from the answer, never echoed from the request. skip_blocked
|
||||
// is a hint: a backend with no cheaper path returns the full numbers,
|
||||
// and a flag echoing the request would then tell a client the scan was
|
||||
// skipped while the numbers beside it prove it was not.
|
||||
BlockedCountSkipped: result.Summary.BlockedIssues == nil,
|
||||
})
|
||||
}
|
||||
95
internal/httpapi/stats_test.go
Normal file
95
internal/httpapi/stats_test.go
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// TestStatsReportsTheSkippedScanFromTheAnswer pins the one derivation this
|
||||
// handler performs: `blocked_count_skipped` comes from the summary's nil
|
||||
// pointers, never from the request that asked for the fast path.
|
||||
//
|
||||
// The role here TAKES the hint, which is the half the roles-path route test
|
||||
// cannot show — its reporter answers with a populated count. Both halves matter
|
||||
// because the two shipped backends differ on it.
|
||||
func TestStatsReportsTheSkippedScanFromTheAnswer(t *testing.T) {
|
||||
reporter := &roleStats{summary: types.Statistics{TotalIssues: 3, OpenIssues: 2}}
|
||||
ts := newTestServer(t, rolesConfig(Config{Stats: reporter}))
|
||||
|
||||
resp := ts.get(t, "/v0/beads/stats?skip_blocked=true")
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
body := decodeBody(t, resp)
|
||||
if body["blocked_count_skipped"] != true {
|
||||
t.Errorf("blocked_count_skipped = %v, want true beside a null blocked_issues", body["blocked_count_skipped"])
|
||||
}
|
||||
summary, _ := body["summary"].(map[string]any)
|
||||
if got, ok := summary["blocked_issues"]; !ok || got != nil {
|
||||
t.Errorf("blocked_issues = %v (present=%t), want an explicit null", got, ok)
|
||||
}
|
||||
if got, ok := summary["ready_issues"]; !ok || got != nil {
|
||||
t.Errorf("ready_issues = %v (present=%t), want an explicit null — the two are nil together", got, ok)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStatsRefusesAnEmptyAssignee pins the refusal the document states: the
|
||||
// workspace-wide question is asked by OMITTING the parameter, so an empty one
|
||||
// is a 400 rather than a summary of the rows nobody is assigned.
|
||||
//
|
||||
// It also pins that the refusal happens BEFORE the role is asked for anything.
|
||||
// A handler that passed the empty string down would get the role's
|
||||
// ErrValidation and answer 500, which tells a client nothing it can act on.
|
||||
func TestStatsRefusesAnEmptyAssignee(t *testing.T) {
|
||||
reporter := &roleStats{}
|
||||
ts := newTestServer(t, rolesConfig(Config{Stats: reporter}))
|
||||
|
||||
resp := ts.get(t, "/v0/beads/stats?assignee=")
|
||||
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) {
|
||||
t.Errorf("code = %v, want %q", body["code"], CodeInvalidArgument)
|
||||
}
|
||||
if body["param"] != "assignee" {
|
||||
t.Errorf("param = %v, want the parameter a client can fix", body["param"])
|
||||
}
|
||||
if len(reporter.statsRequests()) != 0 || len(reporter.assigneeRequests()) != 0 {
|
||||
t.Errorf("the role was asked %d workspace and %d assignee questions, want none: the refusal is before the database slot",
|
||||
len(reporter.statsRequests()), len(reporter.assigneeRequests()))
|
||||
}
|
||||
}
|
||||
|
||||
// TestStatsRefusesAMalformedSkipBlocked pins the other 400 this operation can
|
||||
// produce on its own, which is why invalid_argument is in its row of the
|
||||
// handler table.
|
||||
func TestStatsRefusesAMalformedSkipBlocked(t *testing.T) {
|
||||
ts := newTestServer(t, rolesConfig(Config{Stats: &roleStats{}}))
|
||||
|
||||
resp := ts.get(t, "/v0/beads/stats?skip_blocked=maybe")
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
if body := decodeBody(t, resp); body["param"] != "skip_blocked" {
|
||||
t.Errorf("param = %v, want skip_blocked", body["param"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestStatsRefusesAnUnknownParameter pins that this operation is inside the
|
||||
// document's unknown-parameter rule rather than outside it. Silently ignoring a
|
||||
// parameter is how a client one version ahead of the server acts on an answer
|
||||
// it believes was narrowed.
|
||||
func TestStatsRefusesAnUnknownParameter(t *testing.T) {
|
||||
ts := newTestServer(t, rolesConfig(Config{Stats: &roleStats{}}))
|
||||
|
||||
resp := ts.get(t, "/v0/beads/stats?status=open")
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
if body := decodeBody(t, resp); body["param"] != "status" {
|
||||
t.Errorf("param = %v, want the parameter this server does not know", body["param"])
|
||||
}
|
||||
}
|
||||
|
|
@ -33,6 +33,7 @@ var pinnedSchemas = []struct {
|
|||
{"Dependency", "types.Dependency", types.Dependency{}},
|
||||
{"Comment", "types.Comment", types.Comment{}},
|
||||
{"BondRef", "types.BondRef", types.BondRef{}},
|
||||
{"Statistics", "types.Statistics", types.Statistics{}},
|
||||
}
|
||||
|
||||
// omittedProperties lists JSON field names a pinned schema deliberately does
|
||||
|
|
|
|||
|
|
@ -660,6 +660,9 @@ func (s *configStore) Counter() (issueops.Counter, error) {
|
|||
func (s *configStore) WorkspaceConfig() (issueops.WorkspaceConfig, error) {
|
||||
return nil, &storage.ErrUnsupported{Op: "WorkspaceConfig", Backend: "jira-config-stub"}
|
||||
}
|
||||
func (s *configStore) StatsReporter() (issueops.StatsReporter, error) {
|
||||
return nil, &storage.ErrUnsupported{Op: "StatsReporter", Backend: "jira-config-stub"}
|
||||
}
|
||||
func (s *configStore) SetConfig(_ context.Context, _, _ string) error { return nil }
|
||||
func (s *configStore) SetLocalMetadata(_ context.Context, _, _ string) error { return nil }
|
||||
func (s *configStore) GetLocalMetadata(_ context.Context, _ string) (string, error) {
|
||||
|
|
|
|||
27
internal/storage/dolt/stats_reporter.go
Normal file
27
internal/storage/dolt/stats_reporter.go
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
package dolt
|
||||
|
||||
import (
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/workapi/storestats"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// StatsReporter returns the guarded summary-statistics surface for this store.
|
||||
func (s *DoltStore) StatsReporter() (issueops.StatsReporter, error) {
|
||||
return newStatsReporter(s)
|
||||
}
|
||||
|
||||
// newStatsReporter returns guarded summary statistics backed by store.
|
||||
//
|
||||
// The implementation is the shared one, for the reason newCounter gives: the
|
||||
// two Dolt-backed stores differ below storage.DoltStorage, not above it, so a
|
||||
// second copy here would be a copy of nothing but the constructor. The
|
||||
// statistics QUERIES underneath do differ — each store writes its own
|
||||
// GetStatistics — which is what makes this role's conformance run three
|
||||
// genuine votes instead of two.
|
||||
func newStatsReporter(store *DoltStore) (issueops.StatsReporter, error) {
|
||||
if store == nil {
|
||||
return nil, &storage.ErrUnsupported{Op: "newStatsReporter", Backend: "nil"}
|
||||
}
|
||||
return storestats.New(store)
|
||||
}
|
||||
88
internal/storage/dolt/stats_reporter_contract_test.go
Normal file
88
internal/storage/dolt/stats_reporter_contract_test.go
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
package dolt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/backend/conformance"
|
||||
)
|
||||
|
||||
// TestStatsReporterContract runs the StatsReporter contract against the
|
||||
// server-backed store.
|
||||
//
|
||||
// The cases are subtests of one parent so the whole role suite shares one store
|
||||
// and one copy-on-write branch. That sharing is load-bearing here in a way it
|
||||
// is not for the other roles: a summary takes no predicate, so every
|
||||
// workspace-wide case asserts a BEFORE/AFTER DELTA around its own seeds, and a
|
||||
// delta is only meaningful while nothing else writes to the branch between the
|
||||
// two readings. setupTestStore already marks the PARENT parallel and gives it
|
||||
// its own branch; no subtest here calls t.Parallel.
|
||||
func TestStatsReporterContract(t *testing.T) {
|
||||
fixture, ctx, cleanup := newDoltStatsReporterFixture(t, "sts")
|
||||
defer cleanup()
|
||||
|
||||
t.Run("CountsEveryDurableRowByStatus", func(t *testing.T) {
|
||||
conformance.RunStatsReporterCountsEveryDurableRowByStatus(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ExcludesTheWispTier", func(t *testing.T) {
|
||||
conformance.RunStatsReporterExcludesTheWispTier(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AStatusOutsideTheTalliesIsCountedOnlyInTotal", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAStatusOutsideTheTalliesIsCountedOnlyInTotal(t, ctx, fixture)
|
||||
})
|
||||
t.Run("BlockedCountsTheGraphNotTheStatus", func(t *testing.T) {
|
||||
conformance.RunStatsReporterBlockedCountsTheGraphNotTheStatus(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ReadyIsOpenMinusBlocked", func(t *testing.T) {
|
||||
conformance.RunStatsReporterReadyIsOpenMinusBlocked(t, ctx, fixture)
|
||||
})
|
||||
t.Run("SkipBlockedPairsTheTwoPointers", func(t *testing.T) {
|
||||
conformance.RunStatsReporterSkipBlockedPairsTheTwoPointers(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ExtendedFieldsAreAlwaysZero", func(t *testing.T) {
|
||||
conformance.RunStatsReporterExtendedFieldsAreAlwaysZero(t, ctx, fixture)
|
||||
})
|
||||
t.Run("WritesNothing", func(t *testing.T) {
|
||||
conformance.RunStatsReporterWritesNothing(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AssigneeStatsScopesToOneActor", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAssigneeStatsScopesToOneActor(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AssigneeBlockedCountsTheStatusNotTheGraph", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAssigneeBlockedCountsTheStatusNotTheGraph(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AssigneeStatsMergesTheWispTier", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAssigneeStatsMergesTheWispTier(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AssigneeStatsPopulatesBothPointers", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAssigneeStatsPopulatesBothPointers(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AssigneeStatsRefusesAnEmptyAssignee", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAssigneeStatsRefusesAnEmptyAssignee(t, ctx, fixture)
|
||||
})
|
||||
}
|
||||
|
||||
func newDoltStatsReporterFixture(t *testing.T, prefix string) (conformance.StatsReporterFixture, context.Context, func()) {
|
||||
t.Helper()
|
||||
store, storeCleanup := setupTestStore(t)
|
||||
ctx, cancel := testContext(t)
|
||||
reporter, err := store.StatsReporter()
|
||||
if err != nil {
|
||||
cancel()
|
||||
storeCleanup()
|
||||
t.Fatalf("StatsReporter(): %v", err)
|
||||
}
|
||||
kit := newDoltRoleFixtureKit(store, prefix)
|
||||
fixture := conformance.StatsReporterFixture{
|
||||
IssuePrefix: kit.IssuePrefix,
|
||||
StatsReporter: reporter,
|
||||
CreateIssue: kit.CreateIssue,
|
||||
CreateWisp: kit.CreateWisp,
|
||||
AddDependency: kit.AddDependency,
|
||||
CountHistory: kit.CountHistory,
|
||||
}
|
||||
return fixture, ctx, func() {
|
||||
cancel()
|
||||
storeCleanup()
|
||||
}
|
||||
}
|
||||
28
internal/storage/embeddeddolt/stats_reporter.go
Normal file
28
internal/storage/embeddeddolt/stats_reporter.go
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
//go:build cgo
|
||||
|
||||
package embeddeddolt
|
||||
|
||||
import (
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/workapi/storestats"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// StatsReporter returns the guarded summary-statistics surface for this store.
|
||||
func (s *EmbeddedDoltStore) StatsReporter() (issueops.StatsReporter, error) {
|
||||
return newStatsReporter(s)
|
||||
}
|
||||
|
||||
// newStatsReporter returns guarded summary statistics backed by store.
|
||||
//
|
||||
// The implementation is the shared one: the two Dolt-backed stores differ below
|
||||
// storage.DoltStorage, not above it, so a second copy here would be a copy of
|
||||
// nothing but the constructor. The statistics QUERIES underneath are this
|
||||
// package's own (statistics.go), which is why this backend is a real vote in
|
||||
// the conformance run rather than an engine check on the other's body.
|
||||
func newStatsReporter(store *EmbeddedDoltStore) (issueops.StatsReporter, error) {
|
||||
if store == nil {
|
||||
return nil, &storage.ErrUnsupported{Op: "newStatsReporter", Backend: "nil"}
|
||||
}
|
||||
return storestats.New(store)
|
||||
}
|
||||
|
|
@ -0,0 +1,86 @@
|
|||
//go:build cgo
|
||||
|
||||
package embeddeddolt_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/backend/conformance"
|
||||
)
|
||||
|
||||
// TestStatsReporterContract runs the StatsReporter contract against the
|
||||
// embedded store.
|
||||
//
|
||||
// UNLIKE THE OTHER ROLE WIRINGS IN THIS PACKAGE, this one is a genuine second
|
||||
// vote rather than an engine check. The two stores share the role body
|
||||
// (internal/workapi/storestats), but the statistics QUERIES underneath are this
|
||||
// package's own: embeddeddolt/statistics.go writes its own blocked count and
|
||||
// ready subtraction, in one connection where the server-backed store spends two
|
||||
// read transactions. Only the status tally is shared code.
|
||||
//
|
||||
// One environment for the whole suite: booting an embedded engine per case
|
||||
// would dominate the runtime, and the delta assertions need the subtests
|
||||
// sequential anyway.
|
||||
func TestStatsReporterContract(t *testing.T) {
|
||||
skipUnlessEmbeddedDolt(t)
|
||||
te := newTestEnv(t, "sts")
|
||||
ctx := t.Context()
|
||||
fixture := newEmbeddedStatsReporterFixture(t, te, "sts")
|
||||
|
||||
t.Run("CountsEveryDurableRowByStatus", func(t *testing.T) {
|
||||
conformance.RunStatsReporterCountsEveryDurableRowByStatus(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ExcludesTheWispTier", func(t *testing.T) {
|
||||
conformance.RunStatsReporterExcludesTheWispTier(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AStatusOutsideTheTalliesIsCountedOnlyInTotal", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAStatusOutsideTheTalliesIsCountedOnlyInTotal(t, ctx, fixture)
|
||||
})
|
||||
t.Run("BlockedCountsTheGraphNotTheStatus", func(t *testing.T) {
|
||||
conformance.RunStatsReporterBlockedCountsTheGraphNotTheStatus(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ReadyIsOpenMinusBlocked", func(t *testing.T) {
|
||||
conformance.RunStatsReporterReadyIsOpenMinusBlocked(t, ctx, fixture)
|
||||
})
|
||||
t.Run("SkipBlockedPairsTheTwoPointers", func(t *testing.T) {
|
||||
conformance.RunStatsReporterSkipBlockedPairsTheTwoPointers(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ExtendedFieldsAreAlwaysZero", func(t *testing.T) {
|
||||
conformance.RunStatsReporterExtendedFieldsAreAlwaysZero(t, ctx, fixture)
|
||||
})
|
||||
t.Run("WritesNothing", func(t *testing.T) {
|
||||
conformance.RunStatsReporterWritesNothing(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AssigneeStatsScopesToOneActor", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAssigneeStatsScopesToOneActor(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AssigneeBlockedCountsTheStatusNotTheGraph", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAssigneeBlockedCountsTheStatusNotTheGraph(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AssigneeStatsMergesTheWispTier", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAssigneeStatsMergesTheWispTier(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AssigneeStatsPopulatesBothPointers", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAssigneeStatsPopulatesBothPointers(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AssigneeStatsRefusesAnEmptyAssignee", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAssigneeStatsRefusesAnEmptyAssignee(t, ctx, fixture)
|
||||
})
|
||||
}
|
||||
|
||||
func newEmbeddedStatsReporterFixture(t *testing.T, te *testEnv, prefix string) conformance.StatsReporterFixture {
|
||||
t.Helper()
|
||||
reporter, err := te.store.StatsReporter()
|
||||
if err != nil {
|
||||
t.Fatalf("StatsReporter(): %v", err)
|
||||
}
|
||||
kit := newEmbeddedRoleFixtureKit(te, prefix)
|
||||
return conformance.StatsReporterFixture{
|
||||
IssuePrefix: kit.IssuePrefix,
|
||||
StatsReporter: reporter,
|
||||
CreateIssue: kit.CreateIssue,
|
||||
CreateWisp: kit.CreateWisp,
|
||||
AddDependency: kit.AddDependency,
|
||||
CountHistory: kit.CountHistory,
|
||||
}
|
||||
}
|
||||
16
internal/storage/hook_stats_reporter.go
Normal file
16
internal/storage/hook_stats_reporter.go
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
package storage
|
||||
|
||||
import (
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// StatsReporter returns the inner store's summary-statistics surface.
|
||||
//
|
||||
// It recurses, like every other accessor on this decorator, rather than being
|
||||
// absent: the accessor set is uniform across the chain, so a caller never has
|
||||
// to know which decorators a store is wearing. What it does NOT do is wrap the
|
||||
// result — reporting fires no completion hooks, because nothing completed.
|
||||
// That is the same statement hook_counter.go and hook_issue_reader.go make.
|
||||
func (h *HookFiringStore) StatsReporter() (issueops.StatsReporter, error) {
|
||||
return h.inner.StatsReporter()
|
||||
}
|
||||
|
|
@ -21,6 +21,7 @@ var roleAccessorNames = []string{
|
|||
"IssueRelations",
|
||||
"Counter",
|
||||
"WorkspaceConfig",
|
||||
"StatsReporter",
|
||||
"Commenter",
|
||||
"ReadyClaimer",
|
||||
"BatchCloser",
|
||||
|
|
@ -72,6 +73,7 @@ type roleAccessorStore struct {
|
|||
relations issueops.Relations
|
||||
counter issueops.Counter
|
||||
settings issueops.WorkspaceConfig
|
||||
stats issueops.StatsReporter
|
||||
commenter issueops.Commenter
|
||||
claimer issueops.ReadyClaimer
|
||||
closer issueops.BatchCloser
|
||||
|
|
@ -87,6 +89,7 @@ func newRoleAccessorStore() *roleAccessorStore {
|
|||
relations: sentinel,
|
||||
counter: sentinel,
|
||||
settings: sentinel,
|
||||
stats: sentinel,
|
||||
commenter: sentinel,
|
||||
claimer: sentinel,
|
||||
closer: sentinel,
|
||||
|
|
@ -101,6 +104,9 @@ func (s *roleAccessorStore) Counter() (issueops.Counter, error) { retur
|
|||
func (s *roleAccessorStore) WorkspaceConfig() (issueops.WorkspaceConfig, error) {
|
||||
return s.settings, s.err
|
||||
}
|
||||
func (s *roleAccessorStore) StatsReporter() (issueops.StatsReporter, error) {
|
||||
return s.stats, s.err
|
||||
}
|
||||
func (s *roleAccessorStore) Commenter() (issueops.Commenter, error) { return s.commenter, s.err }
|
||||
func (s *roleAccessorStore) ReadyClaimer() (issueops.ReadyClaimer, error) {
|
||||
return s.claimer, s.err
|
||||
|
|
@ -156,6 +162,12 @@ func (*roleAccessorSentinel) SetSetting(context.Context, issueops.SetSettingRequ
|
|||
func (*roleAccessorSentinel) UnsetSetting(context.Context, issueops.UnsetSettingRequest) (issueops.UnsetSettingResult, error) {
|
||||
return issueops.UnsetSettingResult{}, nil
|
||||
}
|
||||
func (*roleAccessorSentinel) Stats(context.Context, issueops.StatsRequest) (issueops.StatsResult, error) {
|
||||
return issueops.StatsResult{}, nil
|
||||
}
|
||||
func (*roleAccessorSentinel) AssigneeStats(context.Context, issueops.AssigneeStatsRequest) (issueops.StatsResult, error) {
|
||||
return issueops.StatsResult{}, nil
|
||||
}
|
||||
func (*roleAccessorSentinel) AddComment(context.Context, issueops.AddCommentRequest) (issueops.AddCommentResult, error) {
|
||||
return issueops.AddCommentResult{}, nil
|
||||
}
|
||||
|
|
@ -178,14 +190,15 @@ func (*roleAccessorSentinel) RemoveDependency(context.Context, issueops.RemoveDe
|
|||
// satisfying DoltStorage, and silently stops every completion hook on that
|
||||
// role.
|
||||
//
|
||||
// Four roles are asserted the OTHER way round on purpose. Reads fire no
|
||||
// completion hooks, so IssueReader, IssueRelations and Counter deliberately
|
||||
// return the inner surface unwrapped (hook_issue_reader.go, hook_relations.go,
|
||||
// hook_counter.go); WorkspaceConfig does too, and it is the one that is NOT a
|
||||
// read — a settings write changes the workspace rather than a bead, so this
|
||||
// decorator's issue-shaped hook vocabulary has nothing to hand a hook script
|
||||
// (hook_workspace_config.go). This test pins all four as decisions rather than
|
||||
// leaving them indistinguishable from the regression above.
|
||||
// Five roles are asserted the OTHER way round on purpose. Reads fire no
|
||||
// completion hooks, so IssueReader, IssueRelations, Counter and StatsReporter
|
||||
// deliberately return the inner surface unwrapped (hook_issue_reader.go,
|
||||
// hook_relations.go, hook_counter.go, hook_stats_reporter.go); WorkspaceConfig
|
||||
// does too, and it is the one that is NOT a read — a settings write changes the
|
||||
// workspace rather than a bead, so this decorator's issue-shaped hook
|
||||
// vocabulary has nothing to hand a hook script (hook_workspace_config.go).
|
||||
// This test pins all five as decisions rather than leaving them
|
||||
// indistinguishable from the regression above.
|
||||
func TestHookFiringStoreWrapsTheWriteRolesAndPassesTheReadsThrough(t *testing.T) {
|
||||
inner := newRoleAccessorStore()
|
||||
store := NewHookFiringStore(inner, nil)
|
||||
|
|
@ -205,6 +218,7 @@ func TestHookFiringStoreWrapsTheWriteRolesAndPassesTheReadsThrough(t *testing.T)
|
|||
{"IssueRelations", func() (any, error) { return store.IssueRelations() }, inner.relations, false},
|
||||
{"Counter", func() (any, error) { return store.Counter() }, inner.counter, false},
|
||||
{"WorkspaceConfig", func() (any, error) { return store.WorkspaceConfig() }, inner.settings, false},
|
||||
{"StatsReporter", func() (any, error) { return store.StatsReporter() }, inner.stats, false},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
surface, err := test.got()
|
||||
|
|
@ -244,6 +258,7 @@ func TestHookFiringStoreRoleAccessorsPropagateInnerErrors(t *testing.T) {
|
|||
{"IssueRelations", func() (any, error) { return store.IssueRelations() }},
|
||||
{"Counter", func() (any, error) { return store.Counter() }},
|
||||
{"WorkspaceConfig", func() (any, error) { return store.WorkspaceConfig() }},
|
||||
{"StatsReporter", func() (any, error) { return store.StatsReporter() }},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if _, err := test.got(); !errors.Is(err, want) {
|
||||
|
|
|
|||
|
|
@ -157,6 +157,11 @@ type Storage interface {
|
|||
// unchanged, as it is for IssueReader.
|
||||
Counter() (issueops.Counter, error)
|
||||
|
||||
// StatsReporter returns the guarded summary-statistics surface for this
|
||||
// store — `bd status` and its `bd stats` alias. Its own role rather than a
|
||||
// sixth Counter dimension because its numbers are dependency-aware.
|
||||
StatsReporter() (issueops.StatsReporter, error)
|
||||
|
||||
// IssueRelations returns the guarded neighbor-query surface for this
|
||||
// store: the read counterpart of DependencyEditor. It is its own role
|
||||
// rather than a fourth IssueReader method because it answers a question
|
||||
|
|
|
|||
87
internal/storage/uow/stats_reporter.go
Normal file
87
internal/storage/uow/stats_reporter.go
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
package uow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/steveyegge/beads/internal/workapi"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// StatsReporterSource is the capability accessor a unit-of-work provider offers
|
||||
// for the summary-statistics role, the sibling of IssueReaderSource and
|
||||
// CounterSource.
|
||||
type StatsReporterSource interface {
|
||||
StatsReporter() (publicops.StatsReporter, error)
|
||||
}
|
||||
|
||||
// statsReporter answers summary questions through a unit of work.
|
||||
type statsReporter struct {
|
||||
provider UnitOfWorkProvider
|
||||
}
|
||||
|
||||
// StatsReporter returns the guarded summary-statistics surface for this
|
||||
// provider.
|
||||
func (p *doltSQLProvider) StatsReporter() (publicops.StatsReporter, error) {
|
||||
return NewStatsReporter(p)
|
||||
}
|
||||
|
||||
// NewStatsReporter constructs a public summary reporter backed by provider.
|
||||
func NewStatsReporter(provider UnitOfWorkProvider) (publicops.StatsReporter, error) {
|
||||
if isNilUnitOfWorkProvider(provider) {
|
||||
return nil, fmt.Errorf("new stats reporter: unit-of-work provider must not be nil")
|
||||
}
|
||||
return &statsReporter{provider: provider}, nil
|
||||
}
|
||||
|
||||
var _ publicops.StatsReporter = (*statsReporter)(nil)
|
||||
|
||||
// Stats answers the workspace summary inside one read-only unit of work.
|
||||
//
|
||||
// IT DOES NOT TAKE THE SkipBlocked HINT, and that is a property of this seam
|
||||
// rather than an oversight: domain.IssueUseCase publishes GetStatistics and no
|
||||
// no-blocked variant, so there is no cheaper query to run. The alternative —
|
||||
// running the full query and then nilling the two numbers it just computed —
|
||||
// would answer more slowly and tell the caller less, so the hint is ignored
|
||||
// and the full summary is returned. issueops.StatsRequest.SkipBlocked states
|
||||
// that possibility from the caller's side: BlockedIssues being non-nil is how
|
||||
// a caller learns the hint was not taken.
|
||||
func (r *statsReporter) Stats(ctx context.Context, _ publicops.StatsRequest) (publicops.StatsResult, error) {
|
||||
return RunTxRead(ctx, r.provider, func(ctx context.Context, uw UnitOfWork) (publicops.StatsResult, error) {
|
||||
summary, err := uw.IssueUseCase().GetStatistics(ctx)
|
||||
if err != nil {
|
||||
return publicops.StatsResult{}, err
|
||||
}
|
||||
if summary == nil {
|
||||
return publicops.StatsResult{}, nil
|
||||
}
|
||||
return publicops.StatsResult{Summary: *summary}, nil
|
||||
})
|
||||
}
|
||||
|
||||
// AssigneeStats folds one actor's rows and ready work into a summary, through
|
||||
// the same builder and the same fold the store-backed body uses — which is
|
||||
// what makes "your work" mean one thing on both `bd status --assigned` routes.
|
||||
//
|
||||
// BOTH QUERIES SHARE ONE UNIT OF WORK here, where the store seam has no
|
||||
// transaction to share, so this backend's two halves see one snapshot. The
|
||||
// role deliberately does NOT promise that: a contract clause only one of the
|
||||
// implementations can meet is not a contract. What all three share is the
|
||||
// definition of the numbers.
|
||||
func (r *statsReporter) AssigneeStats(ctx context.Context, req publicops.AssigneeStatsRequest) (publicops.StatsResult, error) {
|
||||
assignee, err := workapi.ValidateStatsAssignee(req.Assignee)
|
||||
if err != nil {
|
||||
return publicops.StatsResult{}, err
|
||||
}
|
||||
return RunTxRead(ctx, r.provider, func(ctx context.Context, uw UnitOfWork) (publicops.StatsResult, error) {
|
||||
page, err := uw.IssueUseCase().SearchIssues(ctx, "", workapi.BuildStatsAssigneeIssueFilter(assignee))
|
||||
if err != nil {
|
||||
return publicops.StatsResult{}, err
|
||||
}
|
||||
readyCount := 0
|
||||
if ready, readyErr := uw.IssueUseCase().GetReadyWork(ctx, workapi.BuildStatsAssigneeWorkFilter(assignee)); readyErr == nil {
|
||||
readyCount = len(ready.Items)
|
||||
}
|
||||
return publicops.StatsResult{Summary: workapi.FoldStatsAssigneeSummary(page.Items, readyCount)}, nil
|
||||
})
|
||||
}
|
||||
89
internal/storage/uow/stats_reporter_contract_test.go
Normal file
89
internal/storage/uow/stats_reporter_contract_test.go
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
package uow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/backend/conformance"
|
||||
)
|
||||
|
||||
// TestStatsReporterContract runs the StatsReporter contract against the
|
||||
// unit-of-work provider — the THIRD independent body for this role, not the
|
||||
// second. Both Dolt stores hand back internal/workapi/storestats, but each of
|
||||
// the three spells the blocked count and the ready subtraction itself
|
||||
// (domain/db/issue.go here), so this suite is the only place a disagreement
|
||||
// between the two stores and the use case can surface.
|
||||
//
|
||||
// One provider for the whole suite (each newUOWRoleFixtureProvider boots a real
|
||||
// Dolt sql-server) and NO t.Parallel: the workspace-wide cases assert
|
||||
// before/after deltas on a database this backend does not branch per test, so a
|
||||
// parallel subtest would land rows inside another subtest's arithmetic.
|
||||
func TestStatsReporterContract(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
fixture := newUOWStatsReporterFixture(t, ctx, "sts")
|
||||
|
||||
t.Run("CountsEveryDurableRowByStatus", func(t *testing.T) {
|
||||
conformance.RunStatsReporterCountsEveryDurableRowByStatus(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ExcludesTheWispTier", func(t *testing.T) {
|
||||
conformance.RunStatsReporterExcludesTheWispTier(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AStatusOutsideTheTalliesIsCountedOnlyInTotal", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAStatusOutsideTheTalliesIsCountedOnlyInTotal(t, ctx, fixture)
|
||||
})
|
||||
t.Run("BlockedCountsTheGraphNotTheStatus", func(t *testing.T) {
|
||||
conformance.RunStatsReporterBlockedCountsTheGraphNotTheStatus(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ReadyIsOpenMinusBlocked", func(t *testing.T) {
|
||||
conformance.RunStatsReporterReadyIsOpenMinusBlocked(t, ctx, fixture)
|
||||
})
|
||||
t.Run("SkipBlockedPairsTheTwoPointers", func(t *testing.T) {
|
||||
conformance.RunStatsReporterSkipBlockedPairsTheTwoPointers(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ExtendedFieldsAreAlwaysZero", func(t *testing.T) {
|
||||
conformance.RunStatsReporterExtendedFieldsAreAlwaysZero(t, ctx, fixture)
|
||||
})
|
||||
t.Run("WritesNothing", func(t *testing.T) {
|
||||
conformance.RunStatsReporterWritesNothing(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AssigneeStatsScopesToOneActor", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAssigneeStatsScopesToOneActor(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AssigneeBlockedCountsTheStatusNotTheGraph", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAssigneeBlockedCountsTheStatusNotTheGraph(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AssigneeStatsMergesTheWispTier", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAssigneeStatsMergesTheWispTier(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AssigneeStatsPopulatesBothPointers", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAssigneeStatsPopulatesBothPointers(t, ctx, fixture)
|
||||
})
|
||||
t.Run("AssigneeStatsRefusesAnEmptyAssignee", func(t *testing.T) {
|
||||
conformance.RunStatsReporterAssigneeStatsRefusesAnEmptyAssignee(t, ctx, fixture)
|
||||
})
|
||||
}
|
||||
|
||||
func newUOWStatsReporterFixture(t *testing.T, ctx context.Context, prefix string) conformance.StatsReporterFixture {
|
||||
t.Helper()
|
||||
provider := newUOWRoleFixtureProvider(t, ctx, prefix)
|
||||
// Through the capability accessor, not NewStatsReporter: a provider that
|
||||
// stopped offering the role is the regression, and a constructor call would
|
||||
// hide it.
|
||||
source, ok := provider.(StatsReporterSource)
|
||||
if !ok {
|
||||
t.Fatalf("provider %T does not offer the StatsReporter accessor", provider)
|
||||
}
|
||||
reporter, err := source.StatsReporter()
|
||||
if err != nil {
|
||||
t.Fatalf("StatsReporter(): %v", err)
|
||||
}
|
||||
kit := newUOWRoleFixtureKit(provider, prefix)
|
||||
return conformance.StatsReporterFixture{
|
||||
IssuePrefix: kit.IssuePrefix,
|
||||
StatsReporter: reporter,
|
||||
CreateIssue: kit.CreateIssue,
|
||||
CreateWisp: kit.CreateWisp,
|
||||
AddDependency: kit.AddDependency,
|
||||
CountHistory: kit.CountHistory,
|
||||
}
|
||||
}
|
||||
|
|
@ -22,6 +22,7 @@ var roleAccessorNames = []string{
|
|||
"IssueRelations",
|
||||
"Counter",
|
||||
"WorkspaceConfig",
|
||||
"StatsReporter",
|
||||
"Commenter",
|
||||
"ReadyClaimer",
|
||||
"BatchCloser",
|
||||
|
|
@ -68,6 +69,9 @@ func (s *roleAccessorStore) Counter() (issueops.Counter, error) { retur
|
|||
func (s *roleAccessorStore) WorkspaceConfig() (issueops.WorkspaceConfig, error) {
|
||||
return s.surface, s.err
|
||||
}
|
||||
func (s *roleAccessorStore) StatsReporter() (issueops.StatsReporter, error) {
|
||||
return s.surface, s.err
|
||||
}
|
||||
func (s *roleAccessorStore) Commenter() (issueops.Commenter, error) { return s.surface, s.err }
|
||||
func (s *roleAccessorStore) ReadyClaimer() (issueops.ReadyClaimer, error) {
|
||||
return s.surface, s.err
|
||||
|
|
@ -123,6 +127,12 @@ func (*roleAccessorSentinel) SetSetting(context.Context, issueops.SetSettingRequ
|
|||
func (*roleAccessorSentinel) UnsetSetting(context.Context, issueops.UnsetSettingRequest) (issueops.UnsetSettingResult, error) {
|
||||
return issueops.UnsetSettingResult{}, nil
|
||||
}
|
||||
func (*roleAccessorSentinel) Stats(context.Context, issueops.StatsRequest) (issueops.StatsResult, error) {
|
||||
return issueops.StatsResult{}, nil
|
||||
}
|
||||
func (*roleAccessorSentinel) AssigneeStats(context.Context, issueops.AssigneeStatsRequest) (issueops.StatsResult, error) {
|
||||
return issueops.StatsResult{}, nil
|
||||
}
|
||||
func (*roleAccessorSentinel) AddComment(context.Context, issueops.AddCommentRequest) (issueops.AddCommentResult, error) {
|
||||
return issueops.AddCommentResult{}, nil
|
||||
}
|
||||
|
|
@ -166,6 +176,7 @@ func TestInstrumentedStorageInstrumentsEveryRoleAccessor(t *testing.T) {
|
|||
{"IssueRelations", func() (any, error) { return wrapped.IssueRelations() }},
|
||||
{"Counter", func() (any, error) { return wrapped.Counter() }},
|
||||
{"WorkspaceConfig", func() (any, error) { return wrapped.WorkspaceConfig() }},
|
||||
{"StatsReporter", func() (any, error) { return wrapped.StatsReporter() }},
|
||||
{"Commenter", func() (any, error) { return wrapped.Commenter() }},
|
||||
{"ReadyClaimer", func() (any, error) { return wrapped.ReadyClaimer() }},
|
||||
{"BatchCloser", func() (any, error) { return wrapped.BatchCloser() }},
|
||||
|
|
@ -203,6 +214,7 @@ func TestInstrumentedStorageRoleAccessorsPropagateInnerErrors(t *testing.T) {
|
|||
{"IssueRelations", func() (any, error) { return wrapped.IssueRelations() }},
|
||||
{"Counter", func() (any, error) { return wrapped.Counter() }},
|
||||
{"WorkspaceConfig", func() (any, error) { return wrapped.WorkspaceConfig() }},
|
||||
{"StatsReporter", func() (any, error) { return wrapped.StatsReporter() }},
|
||||
{"Commenter", func() (any, error) { return wrapped.Commenter() }},
|
||||
{"ReadyClaimer", func() (any, error) { return wrapped.ReadyClaimer() }},
|
||||
{"BatchCloser", func() (any, error) { return wrapped.BatchCloser() }},
|
||||
|
|
|
|||
43
internal/telemetry/stats_reporter.go
Normal file
43
internal/telemetry/stats_reporter.go
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// StatsReporter returns the inner store's summary-statistics surface wrapped in
|
||||
// this layer's instrumentation. It recurses instead of delegating: a blind
|
||||
// delegation would return the inner reporter unspanned and untimed.
|
||||
func (s *InstrumentedStorage) StatsReporter() (issueops.StatsReporter, error) {
|
||||
inner, err := s.Unwrap().StatsReporter()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.WrapStatsReporter(inner), nil
|
||||
}
|
||||
|
||||
// WrapStatsReporter instruments guarded summary statistics with this storage
|
||||
// layer's existing telemetry meter and tracer.
|
||||
func (s *InstrumentedStorage) WrapStatsReporter(inner issueops.StatsReporter) issueops.StatsReporter {
|
||||
return &instrumentedStatsReporter{storage: s, inner: inner}
|
||||
}
|
||||
|
||||
type instrumentedStatsReporter struct {
|
||||
storage *InstrumentedStorage
|
||||
inner issueops.StatsReporter
|
||||
}
|
||||
|
||||
func (r *instrumentedStatsReporter) Stats(ctx context.Context, request issueops.StatsRequest) (result issueops.StatsResult, err error) {
|
||||
ctx, span, started := r.storage.op(ctx, "StatsReporter.Stats")
|
||||
result, err = r.inner.Stats(ctx, request)
|
||||
r.storage.done(ctx, span, started, err)
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (r *instrumentedStatsReporter) AssigneeStats(ctx context.Context, request issueops.AssigneeStatsRequest) (result issueops.StatsResult, err error) {
|
||||
ctx, span, started := r.storage.op(ctx, "StatsReporter.AssigneeStats")
|
||||
result, err = r.inner.AssigneeStats(ctx, request)
|
||||
r.storage.done(ctx, span, started, err)
|
||||
return result, err
|
||||
}
|
||||
104
internal/workapi/stats.go
Normal file
104
internal/workapi/stats.go
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
package workapi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// The shared half of issueops.StatsReporter: the assignee-scoped question,
|
||||
// which every implementation answers by asking storage two questions and
|
||||
// folding the answers, rather than by running one aggregate.
|
||||
//
|
||||
// The workspace-wide question needs nothing here. It is a single seam call on
|
||||
// every backend (GetStatistics / GetStatisticsNoBlocked on a store, the use
|
||||
// case's GetStatistics through a unit of work), so there is no request to
|
||||
// translate and a builder for it would be a function that returns nothing.
|
||||
// This file exists because the assignee-scoped answer is ASSEMBLED, and
|
||||
// assembling it twice is how the two front doors would come to disagree about
|
||||
// what "your work" means.
|
||||
|
||||
// ValidateStatsAssignee resolves the actor an assignee-scoped summary answers
|
||||
// for, refusing an empty or whitespace-only one with ErrValidation.
|
||||
//
|
||||
// It returns the value UNCHANGED when it accepts, and the return exists to make
|
||||
// that explicit at every call site: an assignee is an opaque identifier this
|
||||
// layer has no vocabulary for, so trimming it would silently answer for a
|
||||
// different actor than the caller named.
|
||||
func ValidateStatsAssignee(assignee string) (string, error) {
|
||||
if strings.TrimSpace(assignee) == "" {
|
||||
return "", fmt.Errorf("assignee must not be empty for an assignee-scoped summary%.0w", issueops.ErrValidation)
|
||||
}
|
||||
return assignee, nil
|
||||
}
|
||||
|
||||
// BuildStatsAssigneeIssueFilter is the predicate that selects one actor's rows
|
||||
// for the fold below.
|
||||
//
|
||||
// It carries the assignee and NOTHING else, which is a decision and not an
|
||||
// omission: no status restriction (the fold tallies every status, including
|
||||
// closed), no limit (a capped scan would silently under-report a busy actor's
|
||||
// total), and no wisp suppression — the search seam merges the ephemeral tier
|
||||
// unless told not to, and issueops.StatsReporter.AssigneeStats documents the
|
||||
// wider set that produces.
|
||||
func BuildStatsAssigneeIssueFilter(assignee string) types.IssueFilter {
|
||||
return types.IssueFilter{Assignee: &assignee}
|
||||
}
|
||||
|
||||
// BuildStatsAssigneeWorkFilter is the ready-work predicate for the same actor.
|
||||
// It is a second filter type rather than the one above because ready work is a
|
||||
// different question with its own exclusions, which is exactly why
|
||||
// AssigneeStats can report a ready count the workspace-wide answer's
|
||||
// subtraction would not produce.
|
||||
func BuildStatsAssigneeWorkFilter(assignee string) types.WorkFilter {
|
||||
return types.WorkFilter{Assignee: &assignee}
|
||||
}
|
||||
|
||||
// FoldStatsAssigneeSummary turns one actor's rows and their ready-work count
|
||||
// into the summary both front doors print.
|
||||
//
|
||||
// It is the single definition of what `bd status --assigned` means. Everything
|
||||
// it does NOT set is as much a part of that definition as what it does:
|
||||
// PinnedIssues, EpicsEligibleForClosure and AverageLeadTime stay zero, which
|
||||
// AssigneeStats states and this function is the reason for.
|
||||
//
|
||||
// BlockedIssues and ReadyIssues are always non-nil here, including for an actor
|
||||
// with no rows at all. The nil pointers are the workspace-wide answer's
|
||||
// skipped-scan signal (issueops.StatsRequest.SkipBlocked) and mean "not
|
||||
// computed"; this path always computes both, so leaving them nil would render
|
||||
// as "(skipped)" on a summary that skipped nothing.
|
||||
// A nil element is skipped and counted nowhere, TotalIssues included: it is a
|
||||
// row the seam failed to hydrate rather than a row of work, and counting it in
|
||||
// the total while it lands in no status bucket would publish an inconsistency
|
||||
// as data.
|
||||
func FoldStatsAssigneeSummary(issues []*types.Issue, readyCount int) types.Statistics {
|
||||
stats := types.Statistics{}
|
||||
|
||||
blocked := 0
|
||||
for _, issue := range issues {
|
||||
if issue == nil {
|
||||
continue
|
||||
}
|
||||
stats.TotalIssues++
|
||||
switch issue.Status {
|
||||
case types.StatusOpen:
|
||||
stats.OpenIssues++
|
||||
case types.StatusInProgress:
|
||||
stats.InProgressIssues++
|
||||
case types.StatusBlocked:
|
||||
// The STATUS, not the transitive is_blocked flag the
|
||||
// workspace-wide answer counts. The two disagree in both
|
||||
// directions and AssigneeStats says so.
|
||||
blocked++
|
||||
case types.StatusDeferred:
|
||||
stats.DeferredIssues++
|
||||
case types.StatusClosed:
|
||||
stats.ClosedIssues++
|
||||
}
|
||||
}
|
||||
stats.BlockedIssues = &blocked
|
||||
stats.ReadyIssues = &readyCount
|
||||
return stats
|
||||
}
|
||||
128
internal/workapi/stats_test.go
Normal file
128
internal/workapi/stats_test.go
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
package workapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// TestValidateStatsAssignee pins the one refusal on the summary role, and pins
|
||||
// it here because it needs no database: an assignee-scoped summary of nobody is
|
||||
// ErrValidation, and an accepted assignee comes back BYTE-IDENTICAL. The second
|
||||
// half is the load-bearing one — trimming would answer for a different actor
|
||||
// than the caller named, and it is exactly the kind of helpfulness a validator
|
||||
// grows by accident.
|
||||
func TestValidateStatsAssignee(t *testing.T) {
|
||||
for _, blank := range []string{"", " ", "\t\n"} {
|
||||
got, err := ValidateStatsAssignee(blank)
|
||||
if !errors.Is(err, issueops.ErrValidation) {
|
||||
t.Errorf("ValidateStatsAssignee(%q) error = %v, want ErrValidation", blank, err)
|
||||
}
|
||||
if got != "" {
|
||||
t.Errorf("ValidateStatsAssignee(%q) = %q alongside a refusal, want the empty string", blank, got)
|
||||
}
|
||||
}
|
||||
for _, assignee := range []string{"alice", " alice ", "Alice", "agent:worker-3"} {
|
||||
got, err := ValidateStatsAssignee(assignee)
|
||||
if err != nil {
|
||||
t.Errorf("ValidateStatsAssignee(%q): %v", assignee, err)
|
||||
}
|
||||
if got != assignee {
|
||||
t.Errorf("ValidateStatsAssignee(%q) = %q, want it unchanged", assignee, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildStatsAssigneeFiltersCarryOnlyTheAssignee pins what the two
|
||||
// assignee-scoped predicates deliberately leave out. A status restriction, a
|
||||
// limit or a wisp suppression appearing in either of them would change what
|
||||
// `bd status --assigned` counts without changing a line of either front door.
|
||||
func TestBuildStatsAssigneeFiltersCarryOnlyTheAssignee(t *testing.T) {
|
||||
issueFilter := BuildStatsAssigneeIssueFilter("alice")
|
||||
if issueFilter.Assignee == nil || *issueFilter.Assignee != "alice" {
|
||||
t.Fatalf("issue filter assignee = %v, want alice", issueFilter.Assignee)
|
||||
}
|
||||
if issueFilter.Limit != 0 {
|
||||
t.Errorf("issue filter limit = %d, want 0 — a capped scan under-reports a busy actor's total", issueFilter.Limit)
|
||||
}
|
||||
if issueFilter.Status != nil || len(issueFilter.Statuses) != 0 {
|
||||
t.Errorf("issue filter restricts status (%v/%v); the fold tallies every status including closed", issueFilter.Status, issueFilter.Statuses)
|
||||
}
|
||||
if issueFilter.SkipWisps {
|
||||
t.Error("issue filter skips wisps; AssigneeStats documents the merged tier")
|
||||
}
|
||||
|
||||
workFilter := BuildStatsAssigneeWorkFilter("alice")
|
||||
if workFilter.Assignee == nil || *workFilter.Assignee != "alice" {
|
||||
t.Fatalf("work filter assignee = %v, want alice", workFilter.Assignee)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFoldStatsAssigneeSummary is the definition of what `bd status --assigned`
|
||||
// means, checked without a database. It moved here from cmd/bd/status_test.go
|
||||
// with the fold itself: both routes read it from this one function now, so a
|
||||
// change to any number below is a change to both surfaces at once.
|
||||
func TestFoldStatsAssigneeSummary(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
issues []*types.Issue
|
||||
ready int
|
||||
total int
|
||||
open int
|
||||
inProgress int
|
||||
blocked int
|
||||
deferred int
|
||||
closed int
|
||||
}{
|
||||
{
|
||||
name: "counts every status and ready work",
|
||||
issues: []*types.Issue{
|
||||
{Status: types.StatusOpen},
|
||||
{Status: types.StatusInProgress},
|
||||
{Status: types.StatusBlocked},
|
||||
{Status: types.StatusDeferred},
|
||||
{Status: types.StatusClosed},
|
||||
},
|
||||
ready: 2, total: 5, open: 1, inProgress: 1, blocked: 1, deferred: 1, closed: 1,
|
||||
},
|
||||
{
|
||||
name: "empty input retains explicit zero counts",
|
||||
ready: 0,
|
||||
},
|
||||
{
|
||||
// A status outside the five the fold knows lands in the total and
|
||||
// in no bucket, exactly as the workspace-wide answer's tallies do.
|
||||
name: "an unknown status is counted once and bucketed nowhere",
|
||||
issues: []*types.Issue{{Status: types.Status("triage")}, {Status: types.StatusOpen}},
|
||||
ready: 1, total: 2, open: 1,
|
||||
},
|
||||
{
|
||||
name: "a nil row is counted nowhere at all",
|
||||
issues: []*types.Issue{nil, {Status: types.StatusOpen}},
|
||||
ready: 0, total: 1, open: 1,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := FoldStatsAssigneeSummary(tt.issues, tt.ready)
|
||||
if got.TotalIssues != tt.total || got.OpenIssues != tt.open || got.InProgressIssues != tt.inProgress || got.DeferredIssues != tt.deferred || got.ClosedIssues != tt.closed {
|
||||
t.Errorf("FoldStatsAssigneeSummary() = %+v, want total=%d open=%d in_progress=%d deferred=%d closed=%d", got, tt.total, tt.open, tt.inProgress, tt.deferred, tt.closed)
|
||||
}
|
||||
if got.BlockedIssues == nil || *got.BlockedIssues != tt.blocked {
|
||||
t.Errorf("blocked issues = %v, want %d", got.BlockedIssues, tt.blocked)
|
||||
}
|
||||
if got.ReadyIssues == nil || *got.ReadyIssues != tt.ready {
|
||||
t.Errorf("ready issues = %v, want %d", got.ReadyIssues, tt.ready)
|
||||
}
|
||||
// The three fields AssigneeStats says are always zero here. They
|
||||
// are not "not yet implemented" on this path: the fold has no
|
||||
// input that could produce them.
|
||||
if got.PinnedIssues != 0 || got.EpicsEligibleForClosure != 0 || got.AverageLeadTime != 0 {
|
||||
t.Errorf("extended fields = %d/%d/%v, want zeros", got.PinnedIssues, got.EpicsEligibleForClosure, got.AverageLeadTime)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
93
internal/workapi/storestats/reporter.go
Normal file
93
internal/workapi/storestats/reporter.go
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
// Package storestats holds the store-backed implementation of
|
||||
// issueops.StatsReporter: one shared body that every store-shaped backend's
|
||||
// StatsReporter accessor hands back.
|
||||
//
|
||||
// It is a package of its own for the reason internal/workapi/storecounter is —
|
||||
// see that package's doc. A constructor sitting in internal/workapi would be a
|
||||
// one-line drop-in for store.StatsReporter() from any front door, and one that
|
||||
// silently skips the decorators, because a decorator adds its layer in its own
|
||||
// accessor. Down here the only importers are the two Dolt store packages and
|
||||
// the cmd-bd-role-constructors depguard rule in .golangci.yml makes a front
|
||||
// door importing it a lint failure rather than a review comment.
|
||||
//
|
||||
// The accessor is the door. This is the thing behind it.
|
||||
package storestats
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/workapi"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// New returns the summary-statistics surface backed by a store handle.
|
||||
// *DoltStore and *EmbeddedDoltStore answer identically because the difference
|
||||
// between them is below storage.DoltStorage, not above it.
|
||||
func New(store storage.DoltStorage) (issueops.StatsReporter, error) {
|
||||
if store == nil {
|
||||
return nil, &issueops.ErrUnsupported{Op: "storestats.New", Backend: "nil"}
|
||||
}
|
||||
return &storeStatsReporter{store: store}, nil
|
||||
}
|
||||
|
||||
type storeStatsReporter struct{ store storage.DoltStorage }
|
||||
|
||||
var _ issueops.StatsReporter = (*storeStatsReporter)(nil)
|
||||
|
||||
// Stats takes the SkipBlocked hint, because this seam is the one that has a
|
||||
// cheaper path: GetStatisticsNoBlocked runs the status scan and stops, leaving
|
||||
// BlockedIssues and ReadyIssues nil. That pairing is the whole of what the hint
|
||||
// promises, and it is the seam's own — nothing is nilled here.
|
||||
func (r *storeStatsReporter) Stats(ctx context.Context, req issueops.StatsRequest) (issueops.StatsResult, error) {
|
||||
var (
|
||||
summary *types.Statistics
|
||||
err error
|
||||
)
|
||||
if req.SkipBlocked {
|
||||
summary, err = r.store.GetStatisticsNoBlocked(ctx)
|
||||
} else {
|
||||
summary, err = r.store.GetStatistics(ctx)
|
||||
}
|
||||
if err != nil {
|
||||
return issueops.StatsResult{}, err
|
||||
}
|
||||
if summary == nil {
|
||||
// The seam has no documented nil-with-nil-error answer, and a role
|
||||
// that dereferenced one anyway would fault inside whichever front door
|
||||
// asked. An empty workspace is zeros, so that is what an absent
|
||||
// summary becomes.
|
||||
return issueops.StatsResult{}, nil
|
||||
}
|
||||
return issueops.StatsResult{Summary: *summary}, nil
|
||||
}
|
||||
|
||||
// AssigneeStats asks storage its two questions and folds them through the
|
||||
// shared builder, so this route and the unit-of-work route cannot come to
|
||||
// disagree about what one actor's summary means.
|
||||
//
|
||||
// The ready-work failure is reported as zero ready work rather than as an
|
||||
// error, which AssigneeStats documents as this role's one number that may not
|
||||
// be an answer. It is the shipped behavior of both `bd status --assigned`
|
||||
// routes and is kept rather than tightened here: the alternative turns a
|
||||
// summary that is right about five numbers into no summary at all, on the one
|
||||
// query in this role slow enough to time out on a large graph.
|
||||
func (r *storeStatsReporter) AssigneeStats(ctx context.Context, req issueops.AssigneeStatsRequest) (issueops.StatsResult, error) {
|
||||
assignee, err := workapi.ValidateStatsAssignee(req.Assignee)
|
||||
if err != nil {
|
||||
return issueops.StatsResult{}, err
|
||||
}
|
||||
|
||||
issues, err := r.store.SearchIssues(ctx, "", workapi.BuildStatsAssigneeIssueFilter(assignee))
|
||||
if err != nil {
|
||||
return issueops.StatsResult{}, err
|
||||
}
|
||||
|
||||
readyCount := 0
|
||||
if ready, readyErr := r.store.GetReadyWork(ctx, workapi.BuildStatsAssigneeWorkFilter(assignee)); readyErr == nil {
|
||||
readyCount = len(ready)
|
||||
}
|
||||
|
||||
return issueops.StatsResult{Summary: workapi.FoldStatsAssigneeSummary(issues, readyCount)}, nil
|
||||
}
|
||||
|
|
@ -225,6 +225,37 @@ func TestWorkspaceConfigExposesTypedUnsupportedError(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestStatsReporterKeepsTelemetryOutermost is the summary role's version of
|
||||
// the same pin, and the READ answer again: reporting fires no completion hooks,
|
||||
// so the hook decorator recurses and the outermost surface is the instrumented
|
||||
// one.
|
||||
func TestStatsReporterKeepsTelemetryOutermost(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")
|
||||
}
|
||||
|
||||
reporter, err := storage.NewHookFiringStore(instrumented, nil).StatsReporter()
|
||||
if err != nil {
|
||||
t.Fatalf("StatsReporter() error = %v", err)
|
||||
}
|
||||
if got := reflect.TypeOf(reporter).String(); got != "*telemetry.instrumentedStatsReporter" {
|
||||
t.Fatalf("outer layer = %s, want the telemetry wrapper unwrapped by the hook decorator", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsReporterExposesTypedUnsupportedError(t *testing.T) {
|
||||
reporter, err := (*dolt.DoltStore)(nil).StatsReporter()
|
||||
if reporter != nil {
|
||||
t.Fatalf("StatsReporter() reporter = %T, want nil", reporter)
|
||||
}
|
||||
var unsupported *beads.ErrUnsupported
|
||||
if !errors.As(err, &unsupported) {
|
||||
t.Fatalf("StatsReporter() error = %v, want *beads.ErrUnsupported", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCounterExposesTypedUnsupportedError(t *testing.T) {
|
||||
counter, err := (*dolt.DoltStore)(nil).Counter()
|
||||
if counter != nil {
|
||||
|
|
|
|||
|
|
@ -410,14 +410,14 @@ type IssuePage struct {
|
|||
// types.WorkFilter there at all, so no filter is writable there either — both
|
||||
// are directory-scoped with no per-file exception, so a file added to that
|
||||
// package tomorrow is covered the moment it exists. That same forbidigo rule
|
||||
// covers cmd/bd deny-by-default with 63 named exceptions, so the files
|
||||
// covers cmd/bd deny-by-default with 61 named exceptions, so the files
|
||||
// implementing `bd list` and `bd show` cannot write a filter, and neither can
|
||||
// a file they are split or renamed into unless the new name lands on that
|
||||
// list. NOT ENFORCED: the rule forbids NAMING those types, not holding a
|
||||
// value, so the property is "no filter is written there", not "every filter
|
||||
// there came from a builder"; test files are exempt from both rules, because
|
||||
// the oracles hold filters in order to inspect them; `bd ready`'s files are
|
||||
// among the 64, since its listing and --claim are handed the filter itself and
|
||||
// among the 61, since its listing and --claim are handed the filter itself and
|
||||
// the blocked-issue views in those files name one directly, so it is guarded by
|
||||
// the builder and the golden files and not by the linter;
|
||||
// GET /healthz and GET /v0/beads/context are not issue queries and are on no
|
||||
|
|
|
|||
193
issueops/statsreporter.go
Normal file
193
issueops/statsreporter.go
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
package issueops
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
)
|
||||
|
||||
// StatsRequest asks for the workspace's summary statistics. It carries no
|
||||
// predicate at all, and that absence is the type's whole shape: this is a
|
||||
// question about the WORKSPACE, not about a set the caller picked out.
|
||||
//
|
||||
// A caller that wants a number about a set it described calls Counter. The two
|
||||
// roles are told apart by exactly this: CountRequest has thirty filter fields
|
||||
// and no dependency-aware number in its answer; StatsRequest has one
|
||||
// performance knob and every number in its answer is either a status tally of
|
||||
// the whole durable plane or derived from the dependency graph.
|
||||
type StatsRequest struct {
|
||||
// SkipBlocked asks the implementation to answer WITHOUT the blocked-set
|
||||
// scan, which is the expensive half of this query on a large workspace.
|
||||
//
|
||||
// It is a HINT, and the promise is stated from the answer's side rather
|
||||
// than the request's: see StatsReporter.Stats. When it is honored,
|
||||
// StatsResult.Summary.BlockedIssues and .ReadyIssues are both nil; when the
|
||||
// implementation has no cheaper path it answers exactly as if this field
|
||||
// were unset. Nothing else in the result changes either way, so a caller
|
||||
// that does not read the two pointers cannot tell the difference — which is
|
||||
// the point of it being a hint.
|
||||
SkipBlocked bool
|
||||
}
|
||||
|
||||
// AssigneeStatsRequest asks for one actor's summary statistics.
|
||||
//
|
||||
// It is a separate request type, answered by a separate method, rather than an
|
||||
// Assignee field on StatsRequest. That is not ceremony: the two questions
|
||||
// return the same struct and fill FOUR of its fields by different definitions
|
||||
// (see StatsReporter.AssigneeStats). A single request with an optional
|
||||
// Assignee would have made those definitions depend on whether a string was
|
||||
// empty, which is the shape that makes a reader trust a number that means
|
||||
// something else.
|
||||
type AssigneeStatsRequest struct {
|
||||
// Assignee is the actor to answer for, used AS WRITTEN: there is no
|
||||
// trimming, no case folding and no alias expansion, because an assignee is
|
||||
// an opaque identifier this layer has no vocabulary for.
|
||||
//
|
||||
// An empty or whitespace-only value is ErrValidation rather than a query.
|
||||
// An empty assignee would otherwise select the rows whose assignee column
|
||||
// is empty and report them as one actor's workload, and there is no caller
|
||||
// that means that: `bd status --assigned` resolves an actor before it asks,
|
||||
// and an HTTP caller that omits the parameter is asking the workspace-wide
|
||||
// question and gets Stats.
|
||||
Assignee string
|
||||
}
|
||||
|
||||
// StatsResult carries the summary.
|
||||
//
|
||||
// It wraps the CANONICAL struct rather than redeclaring its ten fields, and
|
||||
// that is load-bearing rather than lazy. types.Statistics is what `bd status
|
||||
// --json` marshals under "summary" and what the HTTP operation's `summary`
|
||||
// object is pinned to with x-go-type, so both front doors serialize ONE struct
|
||||
// and neither performs a Go-to-Go mapping on the way to the wire. A result type
|
||||
// of this role's own would have put a translation step between the role and
|
||||
// both surfaces, which is precisely the second wire struct that
|
||||
// internal/httpapi/pinning.go exists to forbid.
|
||||
//
|
||||
// The summary is a VALUE, not a pointer. A role that answered with a pointer
|
||||
// would let a nil-with-nil-error reach a front door that dereferences it — the
|
||||
// hazard internal/httpapi/roles.go wraps checkedReader around Get for — and
|
||||
// there is nothing this role could mean by "no summary": an empty workspace has
|
||||
// statistics, and they are zeros.
|
||||
type StatsResult struct {
|
||||
Summary types.Statistics
|
||||
}
|
||||
|
||||
// StatsReporter describes the summary statistics `bd status` prints and its
|
||||
// `bd stats` alias reprints — and, like Lifecycle, Reader, ReadyClaimer,
|
||||
// BatchCloser, DependencyEditor, Commenter, Relations and Counter, a role with
|
||||
// its own accessor. A new capability gets a new role interface and its own
|
||||
// accessor; never append a method here.
|
||||
//
|
||||
// IT IS ITS OWN ROLE RATHER THAN A SIXTH CountGroup because its numbers are
|
||||
// DEPENDENCY-AWARE. A grouped count partitions rows by a column; two of the
|
||||
// numbers here — the blocked count and the ready count derived from it — come
|
||||
// from the denormalized transitive is_blocked flag the dependency graph
|
||||
// maintains, and no predicate over the issues table can describe them. Counter
|
||||
// says the same thing from its side, and this is the role it points at.
|
||||
//
|
||||
// WHAT THE NUMBERS ARE, and they are not all the same kind of number. Reading
|
||||
// them as "six counts of one set" is the mistake this doc is written to
|
||||
// prevent:
|
||||
//
|
||||
// - TotalIssues, OpenIssues, InProgressIssues, ClosedIssues, DeferredIssues
|
||||
// and PinnedIssues are one scan of the DURABLE issues plane. Every row is
|
||||
// in Total, including closed and pinned ones; the status tallies are exact
|
||||
// equality against the stored status, so a workspace with a custom status
|
||||
// has rows that appear in Total and in none of the four buckets, and the
|
||||
// buckets do not sum to Total. PinnedIssues counts the pinned FLAG and
|
||||
// overlaps every status bucket.
|
||||
// - BlockedIssues counts rows whose transitive is_blocked flag is set,
|
||||
// excluding closed and pinned ones. It is NOT the count of rows whose
|
||||
// status is "blocked", and the two genuinely differ: an open row with an
|
||||
// unfinished blocker is counted here and its status is still "open".
|
||||
// - ReadyIssues is ARITHMETIC, not a query: OpenIssues minus BlockedIssues,
|
||||
// clamped at zero. It is therefore not the cardinality of `bd ready`, which
|
||||
// applies type exclusions, the deferral window, assignee filters and a
|
||||
// limit that none of this touches. A caller that needs the ready-work count
|
||||
// asks the ready-work question; this field is the headline number
|
||||
// `bd status` prints and nothing more.
|
||||
// - EpicsEligibleForClosure and AverageLeadTime are ALWAYS ZERO. No shipped
|
||||
// implementation computes either, on any backend or either front door.
|
||||
// They are carried because types.Statistics is the struct both surfaces
|
||||
// serialize and dropping a field from it is a wire change; they are named
|
||||
// here so a caller does not read a zero as an answer — and so a reader
|
||||
// knows why `bd status`'s "Extended:" branch has never once printed.
|
||||
//
|
||||
// THE WISP TIER IS NOT MERGED into the workspace-wide answer: Stats counts the
|
||||
// durable plane only, which is why an empty workspace full of wisps reports
|
||||
// zero. AssigneeStats does merge it, and says so — one of the four places the
|
||||
// two methods differ.
|
||||
//
|
||||
// Reporting is a READ. Nothing here records a history entry, fires a completion
|
||||
// hook or changes a row, and a refusal changes nothing either. Deterministic
|
||||
// request-validation failures match ErrValidation; result values are
|
||||
// unspecified when error is non-nil. Implementations never mutate caller-owned
|
||||
// request values.
|
||||
//
|
||||
// THE PER-ROLE COST of adding a role like this one is written down in
|
||||
// engdocs/ADDING_AN_ISSUEOPS_ROLE.md.
|
||||
type StatsReporter interface {
|
||||
// Stats returns the workspace summary.
|
||||
//
|
||||
// EMPTY IS ZEROS, NOT AN ERROR. A workspace with no issues answers with a
|
||||
// zero-valued summary and a nil error; there is no ErrNotFound on this
|
||||
// role, for the reason Counter gives — a question about a set has an
|
||||
// answer when the set is empty, and a caller polling a fresh workspace
|
||||
// would otherwise have to classify an error to read a zero.
|
||||
//
|
||||
// SkipBlocked IS A HINT, and this is the whole of its promise:
|
||||
//
|
||||
// - BlockedIssues and ReadyIssues are nil TOGETHER or populated
|
||||
// TOGETHER, never one of each. Readiness is derived from the blocked
|
||||
// count, so there is no state in which one is knowable and the other
|
||||
// is not, and every front door renders on exactly that pairing.
|
||||
// - Nothing else in the summary changes. The other counts are the same
|
||||
// numbers a full call returns.
|
||||
// - Whether the hint was TAKEN is reported by BlockedIssues being nil,
|
||||
// and that is the only report. An implementation with no cheaper path
|
||||
// answers with the full numbers rather than discarding two it already
|
||||
// computed: nilling them to match a stricter contract would trade a
|
||||
// real answer for a slower lie.
|
||||
//
|
||||
// The store-backed implementations take the hint; the unit-of-work seam has
|
||||
// no no-blocked variant and does not. That difference is deliberate,
|
||||
// observable and stated here rather than left for a caller to discover.
|
||||
Stats(ctx context.Context, req StatsRequest) (StatsResult, error)
|
||||
|
||||
// AssigneeStats returns the summary restricted to one actor's rows.
|
||||
//
|
||||
// IT IS THE SAME STRUCT WITH FOUR FIELDS DEFINED DIFFERENTLY, and the
|
||||
// differences are the shipped behavior of `bd status --assigned` rather
|
||||
// than a design anyone would choose fresh:
|
||||
//
|
||||
// - THE SET IS WIDER. It is the actor's rows across the durable plane AND
|
||||
// the ephemeral wisps tier, because the search seam merges the two
|
||||
// unless told not to, where the workspace-wide answer counts the
|
||||
// durable plane only. So this Total is NOT a subset of that one: an
|
||||
// actor holding wisps can report more rows here than Stats reports for
|
||||
// the entire workspace.
|
||||
// - BlockedIssues COUNTS STATUS. Here it is the number of the actor's
|
||||
// rows whose stored status is "blocked" — not the is_blocked flag Stats
|
||||
// reports. The two answer different questions and can disagree in both
|
||||
// directions.
|
||||
// - ReadyIssues IS THE READY-WORK QUERY. Here it is the cardinality of
|
||||
// the actor's ready work — the real dependency-aware question, with its
|
||||
// exclusions — where Stats subtracts two numbers. This one is the
|
||||
// stronger answer, and it is the narrower one.
|
||||
// - PinnedIssues IS ALWAYS ZERO, along with the two fields that are
|
||||
// always zero everywhere. The fold that produces this summary tallies
|
||||
// the five statuses and nothing else.
|
||||
//
|
||||
// A FAILED READY-WORK QUERY IS REPORTED AS ZERO READY WORK, not as an
|
||||
// error: the other five numbers are still right and the summary is still
|
||||
// returned. That is the shipped behavior of both `bd status --assigned`
|
||||
// routes, published here rather than quietly tightened, and it is the one
|
||||
// place this role can hand back a number that is not an answer. A caller
|
||||
// that must not confuse "none ready" with "could not tell" asks the
|
||||
// ready-work question directly, where the failure is its own.
|
||||
//
|
||||
// An empty or whitespace-only Assignee is ErrValidation. An assignee that
|
||||
// matches nothing is a zero-valued summary and a nil error, not a miss:
|
||||
// "this actor has no work" is an answer.
|
||||
AssigneeStats(ctx context.Context, req AssigneeStatsRequest) (StatsResult, error)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue