feat(delete): put bd delete behind the Deleter role and converge both routes (bd-x82so)
THE TWO ROUTES DISAGREED ABOUT WHAT --force MEANS on a destructive command.
On a local database `--force` deletes the named beads and orphans their
dependents; on a team server it deleted the whole dependent subtree, `--cascade`
was REFUSED outright ("not supported in proxied-server mode (delete always
cascades)") and Cascade was hardcoded true at both call sites. So there was no
way to delete one bead on a team server without taking everything under it, and
asking for the safer behaviour was an error.
Q1 ANSWERED IN THE ROLE. issueops.Deleter has one method, reached through
store.Deleter() and the provider's own accessor, and the three modes are request
fields: no flags refuses over a dependent the request did not name, Force
orphans it, Cascade deletes the closure. The guard is workapi's and the body's,
below every front door, for the reason Sweeper's require-a-filter gate is: a
second front door that inherited the capability without the guard would orphan a
workspace's graph by omission — which is exactly what this commit's HTTP
operation would otherwise have been.
IT IS A DIFFERENT ROLE FROM Sweeper, not a mode of it. Sweeper erases a set the
caller DESCRIBED; this erases rows the caller NAMED. That is what decides where
each one's safety lives: a description can be accidentally too wide, so Sweeper
carries a require-a-filter refusal; a list of ids cannot be, so this one's guard
is about the graph.
THE DEFECT. The direct route's batch path deleted the rows in one transaction
and then rewrote `[deleted:ID]` into the neighbours' text afterwards, discarding
every update error. A failure in the window left a workspace whose beads were
gone and whose descriptions still cited them by id. The existence probe, the
guard, the cascade expansion, the deletion and the rewrite are now one
transaction. WHAT THAT COSTS is written into the leaf beside the promise: the
transaction is as large as the deletion plus its neighbourhood, so a batch with
a very large neighbourhood fails whole. It is NOT Sweeper's trade (bd-hysee) —
the delete itself was already one transaction on every route — and the part that
is new is named rather than measured, which is recorded for sign-off.
TWO MORE DEFECTS the single call site removed. The one-id path held its own
transaction that removed each edge by hand, so it never reported labels, events
or orphans; and `domain.DeleteIssuesParams.EnforceCascadePolicy` and `.Force`
were declared, documented in fifteen lines describing exactly these three modes,
and READ BY NOTHING. They are deleted; the policy lives in the role now.
THE CONTRACT IS WHAT WAS DELETED, not what was reported.
backend/conformance/deleter_contract.go holds eleven cases, each citing the leaf
doc, run at all three backends with ZERO PARKS and zero divergences. Every case
that acts asserts row counts through QueryScalar rather than trusting the result
the delete reported about itself. They are TWO INDEPENDENT BODIES plus an engine
check: dolt and embeddeddolt share internal/storage/issueops.DeleteInTx and
differ only in how they reach a transaction, and the unit-of-work provider
reaches the same questions through the domain use cases. It does NOT duplicate
backend/conformance/audit_issue-lifecycle.go, which stays the right home for
`DeleteIssues` at the STORAGE seam: that suite's Factory hands back a bare
storage.DoltStorage, so the unit-of-work backend — where the guard did not exist
at all before this commit — can never run a case placed there.
`bd serve` gains POST /v0/beads/issues:delete, spec first. The dependents guard,
the all-or-nothing id resolution and the reference rewrite are the role's, so
the handler is argument validation and a projection. `cascade` and `force`
default false, which is the guarded mode; DeleteIssuesResult is not
x-go-type-pinned for the reason SweepResult is not, and a reflection test keeps
the projection honest. No page envelope, so nothing to pin in pinning.go.
USER-VISIBLE, and the CHANGELOG says so loudly: a team-server script relying on
the implicit cascade starts leaving orphans; `bd delete <one-id>` without
--force now refuses over an outside dependent, converging the direct route's
three paths onto the answer two of them already gave; the proxied `--json`
result gains `orphaned_issues`. Reasoning and the alternatives are in
/data/tmp/sd-server/AMBIGUITIES.md as A-del-1..6.
Verified: build, vet, gofmt clean; golangci-lint 0 issues; make api-check
(regenerate-and-diff plus the httpapi suite) green; TestDeleterContract 11/11 at
dolt, embeddeddolt and uow; the internal/workapi delete unit tests; the
internal/storage, internal/telemetry and root layering pins;
TestConformance/Audit/issue-lifecycle and the dolt TestDeleteIssues* family
(this commit refactors DeleteIssuesInTx's guard); TestEmbeddedDelete,
TestEmbeddedDeleteJSONDependencyErrorContract, TestBurnWisps,
TestWispGCProtectsActiveWisps and TestCLI_WispGCExcludeType under
BEADS_TEST_EMBEDDED_DOLT=1; TestProxiedServerDelete{,ForceOrphans,Wisp,
Concurrent}, TestProxiedServerMolBurn and TestProxiedServerWispGC under
BEADS_TEST_PROXIED_SERVER=1; and TestProxiedLookup*.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
d10a388340
commit
cf0a42cdae
39 changed files with 3591 additions and 450 deletions
57
CHANGELOG.md
57
CHANGELOG.md
|
|
@ -57,6 +57,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
is no cursor and no `offset`: a predicate query's matching set is assembled
|
||||
outside the database, so there is no keyset position to encode. `capabilities`
|
||||
gains `issues.query`.
|
||||
- **`POST /v0/beads/issues:delete` — deleting named beads over HTTP**
|
||||
(bd-x82so). `bd serve` gains the second destructive operation on its surface:
|
||||
a body of `ids` plus `cascade`, `force` and `dry_run`, answering with the
|
||||
counts and the orphan list. It calls the same `issueops.Deleter` `bd delete`
|
||||
calls, so the dependents guard, the all-or-nothing id resolution and the
|
||||
reference rewrite are the library's rather than the handler's — the endpoint
|
||||
cannot orphan a graph by omission. `cascade` and `force` both default false,
|
||||
which is the guarded mode. `capabilities` gains `issues.delete`.
|
||||
- **`POST /v0/beads/issues:batchCreate` — creating many issues over HTTP**
|
||||
(bd-lu170). `bd serve` gains the second write on its surface and the first
|
||||
one that creates rows: a request carrying an `actor` and up to 100 items is
|
||||
|
|
@ -333,6 +341,55 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
|
||||
### Changed
|
||||
|
||||
- **`bd delete --force` on a TEAM SERVER now orphans dependents instead of
|
||||
deleting them** (bd-x82so). **Read this one before you upgrade a team-server
|
||||
script.**
|
||||
|
||||
Against a proxied server, `bd delete X --force` used to delete X *and its
|
||||
whole dependent subtree*, and `--cascade` was refused outright with "not
|
||||
supported in proxied-server mode (delete always cascades)". There was no way
|
||||
to delete one bead on a team server without taking everything that depended on
|
||||
it, and asking for the safer behaviour was an error.
|
||||
|
||||
Both routes now mean the same three things by the same two flags, which are
|
||||
the local database's meanings, unchanged:
|
||||
|
||||
| you type | you get |
|
||||
|---|---|
|
||||
| `bd delete X` | REFUSED if anything outside the request depends on X |
|
||||
| `bd delete X --force` | X is deleted; its dependents survive, ORPHANED |
|
||||
| `bd delete X --cascade --force` | X and its whole dependent subtree are deleted |
|
||||
|
||||
**A team-server script that relied on the implicit cascade will start leaving
|
||||
orphans.** Add `--cascade` to it. The proxied `--json` result gains
|
||||
`orphaned_issues` so a script can see them; a cascade leaves it null.
|
||||
|
||||
- **`bd delete <one-id>` without `--force` now REFUSES when the bead has an
|
||||
outside dependent**, instead of printing a preview and exiting 0 (bd-x82so).
|
||||
This is the direct route converging with itself: the multi-id path and
|
||||
`--dry-run` have always refused here, and only the unconfirmed one-id preview
|
||||
did not. The refusal names the bead and says to use `--cascade` or `--force`,
|
||||
which is the same sentence the other two paths already printed.
|
||||
|
||||
- **`bd delete` rewrites text references INSIDE the delete transaction**
|
||||
(bd-x82so). The direct route deleted the rows in one transaction and then
|
||||
rewrote `[deleted:ID]` into the neighbouring beads' descriptions afterwards,
|
||||
discarding every update error it got; a failure in the window left a workspace
|
||||
whose beads were gone and whose descriptions still cited them by id. The whole
|
||||
operation — the existence probe, the dependents guard, the cascade expansion,
|
||||
the deletion and the rewrite — is now one transaction on the new
|
||||
`issueops.Deleter` role, shared by both routes and by `bd serve`.
|
||||
|
||||
**The trade, said out loud:** the transaction is now as large as the deletion
|
||||
plus its graph neighbourhood, so a delete whose neighbourhood is big enough to
|
||||
exceed the backend's write timeout fails whole instead of deleting the beads
|
||||
and leaving the text stale. Split a very large `--from-file` batch.
|
||||
|
||||
- **`bd delete` refuses the whole request when any id names no bead**
|
||||
(bd-x82so), on both routes and under `--dry-run`. The multi-id path already
|
||||
did; the guarantee is now the role's, so nothing partial is deleted before the
|
||||
typo is reported.
|
||||
|
||||
- **`bd purge` and `bd prune` select and delete in ONE transaction** (bd-pn231).
|
||||
The direct route used to search in one transaction and delete in another, so a
|
||||
bead closed between the two could be counted and not deleted, or deleted and
|
||||
|
|
|
|||
604
backend/conformance/deleter_contract.go
Normal file
604
backend/conformance/deleter_contract.go
Normal file
|
|
@ -0,0 +1,604 @@
|
|||
package conformance
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// This file holds the semantic contract every implementation of
|
||||
// publicops.Deleter must satisfy. Each case asserts what issueops/deleter.go
|
||||
// PROMISES, cited by line, rather than what any one backend happens to do; a
|
||||
// backend that genuinely disagrees is parked at its own wiring site with
|
||||
// skipKnownDivergence so the case still runs on the ones that agree.
|
||||
//
|
||||
// THERE ARE TWO BODIES BEHIND THE THREE WIRINGS. dolt and embeddeddolt share
|
||||
// internal/storage/issueops.DeleteInTx and differ only in how they reach a
|
||||
// transaction; the unit-of-work provider reaches the same questions through the
|
||||
// domain use cases and is genuinely separate code. So the wirings are one vote
|
||||
// plus an engine check, and a second independent vote.
|
||||
//
|
||||
// WHAT THE AUDIT SUITE ALREADY COVERS, AND WHY THIS IS NOT A SECOND COPY OF IT.
|
||||
// backend/conformance/audit_issue-lifecycle.go pins cascade, force, the orphan
|
||||
// guard and the dry-run counts at the STORAGE SEAM — `DeleteIssues` on
|
||||
// storage.DoltStorage — and it stays the right home for that method, which
|
||||
// `bd gc`, `bd wisp` and the sweeper still call directly. It cannot see the
|
||||
// role: its Factory hands back a bare storage.DoltStorage, so the unit-of-work
|
||||
// provider — the backend where the guard did not exist at all before this
|
||||
// commit — never runs a case placed there. The cases below are therefore
|
||||
// deliberately NOT that method's cases repeated: they are about the promises
|
||||
// the ROLE adds on top of it, which the storage seam has no opinion on —
|
||||
// id normalization, the ordered refusals, the typed errors, the reference
|
||||
// rewrite inside the transaction, and the history entry.
|
||||
//
|
||||
// EVERY CASE NAMESPACES ITS SEEDS with fixture.IssuePrefix and its own tag,
|
||||
// because the three wirings share one database across the whole role suite and
|
||||
// a delete is one of the two operations here that can destroy another case's
|
||||
// fixture. Unlike the sweeper's cases they do not need a pattern to scope the
|
||||
// OPERATION — a delete only ever touches ids it was handed — so the namespacing
|
||||
// is about collisions rather than about blast radius.
|
||||
|
||||
// DeleterFixture supplies adapter-specific storage access for the named-row
|
||||
// erasure 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 DeleterFixture struct {
|
||||
// IssuePrefix namespaces the ids each assertion seeds, so several of them
|
||||
// can share one database.
|
||||
IssuePrefix string
|
||||
// Deleter is the surface under test.
|
||||
Deleter publicops.Deleter
|
||||
// CreateIssue seeds a durable issue in the issues plane.
|
||||
CreateIssue func(context.Context, *types.Issue, string) error
|
||||
// CreateWisp seeds an ephemeral issue in the wisps plane.
|
||||
CreateWisp func(context.Context, *types.Issue, string) error
|
||||
// AddDependency seeds ONE edge, routed to the plane the edge's SOURCE
|
||||
// lives in. It is what makes a dependent, which is what this role's guard
|
||||
// is about.
|
||||
AddDependency func(context.Context, *types.Dependency, string) error
|
||||
// QueryScalar runs a single-row query and scans it. It is how these cases
|
||||
// observe the ONE thing a delete result cannot be trusted to report about
|
||||
// itself: whether the rows are really gone.
|
||||
QueryScalar func(context.Context, string, []any, ...any) 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)
|
||||
}
|
||||
|
||||
// RunDeleterRefusesAMalformedRequest pins the request rules that need no
|
||||
// database (issueops/deleter.go, DeleteRequest.IDs: "an empty or all-blank
|
||||
// slice is ErrValidation rather than a no-op").
|
||||
//
|
||||
// A no-op would be the dangerous answer here rather than merely a sloppy one:
|
||||
// a caller whose id list came out empty because its own construction broke
|
||||
// would read "deleted 0" and conclude the workspace was already clean.
|
||||
func RunDeleterRefusesAMalformedRequest(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
request publicops.DeleteRequest
|
||||
}{
|
||||
{"no ids", publicops.DeleteRequest{Force: true}},
|
||||
{"nil ids", publicops.DeleteRequest{IDs: nil, Force: true}},
|
||||
{"blank id", publicops.DeleteRequest{IDs: []string{" "}, Force: true}},
|
||||
{"blank id beside a real one", publicops.DeleteRequest{IDs: []string{"x", ""}, Force: true}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
result, err := fixture.Deleter.Delete(ctx, test.request)
|
||||
if !errors.Is(err, publicops.ErrValidation) {
|
||||
t.Fatalf("Delete(%s) error = %v, want ErrValidation", test.name, err)
|
||||
}
|
||||
if result.Deleted != 0 {
|
||||
t.Errorf("refused delete reported Deleted = %d, want 0", result.Deleted)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// RunDeleterRefusesAnAbsentID pins the all-or-nothing promise
|
||||
// (issueops/deleter.go, DeleteRequest.IDs: "An id that names none is
|
||||
// ErrNotFound and NOTHING IS DELETED — not even the ids beside it that did
|
||||
// resolve").
|
||||
//
|
||||
// It is asserted with a REAL id beside the typo, because that is the only
|
||||
// arrangement that can fail: an implementation that deleted as it resolved
|
||||
// would pass a single-absent-id case perfectly and still have erased the row
|
||||
// this one seeds. And it is asserted under DryRun too, because the leaf
|
||||
// promises a preview refuses where the real run refuses — a preview that
|
||||
// succeeded here would tell a caller to go ahead.
|
||||
func RunDeleterRefusesAnAbsentID(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
stored := deleterSeedIssue(t, ctx, fixture, "gone", "real")
|
||||
absent := fixture.IssuePrefix + "-gone-nosuchrow"
|
||||
|
||||
for _, dryRun := range []bool{false, true} {
|
||||
result, err := fixture.Deleter.Delete(ctx, publicops.DeleteRequest{
|
||||
IDs: []string{stored, absent},
|
||||
Force: true,
|
||||
DryRun: dryRun,
|
||||
})
|
||||
if !errors.Is(err, publicops.ErrNotFound) {
|
||||
t.Fatalf("Delete(dryRun=%v) with an absent id error = %v, want ErrNotFound", dryRun, err)
|
||||
}
|
||||
var notFound *publicops.NotFoundError
|
||||
if !errors.As(err, ¬Found) {
|
||||
t.Fatalf("Delete(dryRun=%v) error = %v, want *NotFoundError", dryRun, err)
|
||||
}
|
||||
if !reflect.DeepEqual(notFound.IDs, []string{absent}) {
|
||||
t.Errorf("NotFoundError.IDs = %v, want [%s] — the id that resolved is not missing", notFound.IDs, absent)
|
||||
}
|
||||
if result.Deleted != 0 {
|
||||
t.Errorf("refused delete reported Deleted = %d, want 0", result.Deleted)
|
||||
}
|
||||
deleterAssertIssueRows(t, ctx, fixture, 1, stored)
|
||||
}
|
||||
}
|
||||
|
||||
// RunDeleterRefusesDependentsOutsideTheRequest pins the guard this role took
|
||||
// off the CLI (issueops/deleter.go, DeleteRequest.Force: "WITHOUT Cascade AND
|
||||
// WITHOUT Force, a named row that some row OUTSIDE the request depends on is
|
||||
// refused"), and the exception beside it: a dependent the request DID name is
|
||||
// not a dependent for this purpose.
|
||||
//
|
||||
// The refusal is asserted with its EFFECT as well as its type. A guard that
|
||||
// returned the error after deleting would satisfy an errors.Is assertion
|
||||
// perfectly, and on this operation that is the failure worth spending seeded
|
||||
// rows to rule out.
|
||||
func RunDeleterRefusesDependentsOutsideTheRequest(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
blocker := deleterSeedIssue(t, ctx, fixture, "guard", "blocker")
|
||||
dependent := deleterSeedIssue(t, ctx, fixture, "guard", "dependent")
|
||||
deleterAddEdge(t, ctx, fixture, dependent, blocker)
|
||||
|
||||
for _, dryRun := range []bool{false, true} {
|
||||
result, err := fixture.Deleter.Delete(ctx, publicops.DeleteRequest{
|
||||
IDs: []string{blocker},
|
||||
DryRun: dryRun,
|
||||
})
|
||||
if !errors.Is(err, publicops.ErrDependentsOutsideRequest) {
|
||||
t.Fatalf("Delete(dryRun=%v) unforced over a dependent: error = %v, want ErrDependentsOutsideRequest", dryRun, err)
|
||||
}
|
||||
var blocked *publicops.DependentsOutsideRequestError
|
||||
if !errors.As(err, &blocked) {
|
||||
t.Fatalf("Delete(dryRun=%v) error = %v, want *DependentsOutsideRequestError", dryRun, err)
|
||||
}
|
||||
if blocked.IssueID != blocker {
|
||||
t.Errorf("DependentsOutsideRequestError.IssueID = %q, want %q", blocked.IssueID, blocker)
|
||||
}
|
||||
if !reflect.DeepEqual(blocked.Dependents, []string{dependent}) {
|
||||
t.Errorf("DependentsOutsideRequestError.Dependents = %v, want [%s]", blocked.Dependents, dependent)
|
||||
}
|
||||
if result.Deleted != 0 {
|
||||
t.Errorf("refused delete reported Deleted = %d, want 0", result.Deleted)
|
||||
}
|
||||
deleterAssertIssueRows(t, ctx, fixture, 2, blocker, dependent)
|
||||
}
|
||||
|
||||
// Naming BOTH ends is not a guarded case: the request is deleting the edge
|
||||
// too. Refusing it would make `bd delete a b` fail on exactly the pair a
|
||||
// caller took care to list together.
|
||||
result, err := fixture.Deleter.Delete(ctx, publicops.DeleteRequest{IDs: []string{blocker, dependent}})
|
||||
if err != nil {
|
||||
t.Fatalf("Delete() naming both ends of the edge: error = %v, want nil — a dependent INSIDE the request is not a dependent", err)
|
||||
}
|
||||
if result.Deleted != 2 {
|
||||
t.Errorf("Deleted = %d, want 2", result.Deleted)
|
||||
}
|
||||
deleterAssertIssueRows(t, ctx, fixture, 0, blocker, dependent)
|
||||
}
|
||||
|
||||
// RunDeleterForceOrphansDependents pins what --force MEANS after this commit
|
||||
// (issueops/deleter.go, DeleteRequest.Force: "deletes the named rows and leaves
|
||||
// rows that depended on them ORPHANED"), and it is the case that would have
|
||||
// caught the drift this commit removes: the proxied route used to hardcode
|
||||
// cascade, so `--force` there deleted the dependent instead of orphaning it.
|
||||
//
|
||||
// DeleteResult.Orphaned is asserted alongside the surviving row, because the
|
||||
// number a caller acts on and the row that is actually there are two different
|
||||
// claims and only one of them was ever true on that route.
|
||||
func RunDeleterForceOrphansDependents(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
blocker := deleterSeedIssue(t, ctx, fixture, "force", "blocker")
|
||||
dependent := deleterSeedIssue(t, ctx, fixture, "force", "dependent")
|
||||
deleterAddEdge(t, ctx, fixture, dependent, blocker)
|
||||
|
||||
result := deleterDelete(t, ctx, fixture, publicops.DeleteRequest{
|
||||
IDs: []string{blocker},
|
||||
Force: true,
|
||||
})
|
||||
if result.Deleted != 1 {
|
||||
t.Errorf("Deleted = %d, want 1 — force deletes the NAMED row and nothing else", result.Deleted)
|
||||
}
|
||||
if !reflect.DeepEqual(result.Orphaned, []string{dependent}) {
|
||||
t.Errorf("Orphaned = %v, want [%s]", result.Orphaned, dependent)
|
||||
}
|
||||
deleterAssertIssueRows(t, ctx, fixture, 0, blocker)
|
||||
deleterAssertIssueRows(t, ctx, fixture, 1, dependent)
|
||||
// The orphan keeps its row and loses its edge; a dependent still pointing
|
||||
// at a deleted id would be a dangling edge rather than an orphan.
|
||||
deleterAssertEdgeRows(t, ctx, fixture, 0, dependent, blocker)
|
||||
}
|
||||
|
||||
// RunDeleterCascadeDeletesTheClosure pins the other mode (issueops/deleter.go,
|
||||
// DeleteRequest.Cascade) over a chain rather than a single edge, because
|
||||
// "transitive" is the whole claim and a one-edge fixture cannot tell a
|
||||
// transitive expansion from a direct one.
|
||||
//
|
||||
// It also pins the interaction the leaf spells out: a request carrying BOTH
|
||||
// Cascade and Force is legal and behaves as Cascade, with Orphaned empty —
|
||||
// there is nothing left outside the closure to orphan.
|
||||
func RunDeleterCascadeDeletesTheClosure(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
root := deleterSeedIssue(t, ctx, fixture, "casc", "root")
|
||||
middle := deleterSeedIssue(t, ctx, fixture, "casc", "middle")
|
||||
leaf := deleterSeedIssue(t, ctx, fixture, "casc", "leaf")
|
||||
bystander := deleterSeedIssue(t, ctx, fixture, "casc", "bystander")
|
||||
deleterAddEdge(t, ctx, fixture, middle, root)
|
||||
deleterAddEdge(t, ctx, fixture, leaf, middle)
|
||||
|
||||
result := deleterDelete(t, ctx, fixture, publicops.DeleteRequest{
|
||||
IDs: []string{root},
|
||||
Cascade: true,
|
||||
Force: true,
|
||||
})
|
||||
if result.Deleted != 3 {
|
||||
t.Errorf("Deleted = %d, want 3 — the closure is root, its dependent and ITS dependent", result.Deleted)
|
||||
}
|
||||
if len(result.Orphaned) != 0 {
|
||||
t.Errorf("Orphaned = %v, want empty: a cascade leaves nothing outside the set to orphan", result.Orphaned)
|
||||
}
|
||||
deleterAssertIssueRows(t, ctx, fixture, 0, root, middle, leaf)
|
||||
deleterAssertIssueRows(t, ctx, fixture, 1, bystander)
|
||||
}
|
||||
|
||||
// RunDeleterErasesAcrossBothPlanes pins that one request reaches BOTH tiers
|
||||
// (issueops/deleter.go, DeleteRequest.IDs: "in either plane").
|
||||
//
|
||||
// It is the case the storage seam's own suite cannot stand in for, because the
|
||||
// role is where a front door's mixed id list arrives: `bd delete` takes
|
||||
// whatever ids the caller names and one `--from-file` batch may legitimately
|
||||
// mix a wisp with an issue. A body that routed the whole request by one flag
|
||||
// would delete the issue and silently report the wisp as gone.
|
||||
func RunDeleterErasesAcrossBothPlanes(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
issue := deleterSeedIssue(t, ctx, fixture, "plane", "issue")
|
||||
wisp := deleterSeedWisp(t, ctx, fixture, "plane", "wisp")
|
||||
|
||||
result := deleterDelete(t, ctx, fixture, publicops.DeleteRequest{
|
||||
IDs: []string{issue, wisp},
|
||||
Force: true,
|
||||
})
|
||||
if result.Deleted != 2 {
|
||||
t.Errorf("Deleted = %d, want 2 — one row from each plane", result.Deleted)
|
||||
}
|
||||
deleterAssertIssueRows(t, ctx, fixture, 0, issue)
|
||||
deleterAssertWispRows(t, ctx, fixture, 0, wisp)
|
||||
}
|
||||
|
||||
// RunDeleterCollapsesDuplicateIDs pins the normalization (issueops/deleter.go,
|
||||
// DeleteRequest.IDs: "DUPLICATES COLLAPSE"). An id repeated in a `--from-file`
|
||||
// list is one row, and an implementation that did not collapse would either
|
||||
// double-count the answer or fail its second DELETE.
|
||||
func RunDeleterCollapsesDuplicateIDs(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
id := deleterSeedIssue(t, ctx, fixture, "dupe", "target")
|
||||
|
||||
result := deleterDelete(t, ctx, fixture, publicops.DeleteRequest{
|
||||
IDs: []string{id, id, " " + id + " "},
|
||||
Force: true,
|
||||
})
|
||||
if result.Deleted != 1 {
|
||||
t.Errorf("Deleted = %d, want 1 for one id named three times", result.Deleted)
|
||||
}
|
||||
deleterAssertIssueRows(t, ctx, fixture, 0, id)
|
||||
}
|
||||
|
||||
// RunDeleterRewritesReferencesInNeighbors pins the rewrite
|
||||
// (issueops/deleter.go, Deleter.Delete: "WHICH ROWS GET REWRITTEN"): every
|
||||
// occurrence of a deleted id in a graph neighbor's four long text fields
|
||||
// becomes `[deleted:<id>]`, matched at word boundaries.
|
||||
//
|
||||
// The NEGATIVE half is the half worth having. A neighbor also cites an id that
|
||||
// merely has the deleted one as a PREFIX, and that citation must survive
|
||||
// untouched: a rewrite that used a bare substring match would corrupt a
|
||||
// bystander's text on every delete, and no count in the result would show it.
|
||||
func RunDeleterRewritesReferencesInNeighbors(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
target := deleterSeedIssue(t, ctx, fixture, "refs", "target")
|
||||
// An id the target's id is a strict prefix of, so the word-boundary rule
|
||||
// has something to get wrong.
|
||||
lookalike := deleterSeedIssue(t, ctx, fixture, "refs", "targetx")
|
||||
|
||||
neighbor := deleterIssue(fixture, "refs", "neighbor", false)
|
||||
neighbor.Description = "blocked by " + target + "."
|
||||
neighbor.Notes = "see " + target + " and " + lookalike
|
||||
neighbor.Design = "(" + target + ")"
|
||||
neighbor.AcceptanceCriteria = target + " closes"
|
||||
deleterSeed(t, ctx, fixture, neighbor)
|
||||
deleterAddEdge(t, ctx, fixture, neighbor.ID, target)
|
||||
|
||||
// A row that CITES the target but shares no edge with it. The leaf says
|
||||
// the rewrite is scoped to graph neighbors, so this one is left alone.
|
||||
stranger := deleterIssue(fixture, "refs", "stranger", false)
|
||||
stranger.Description = "also mentions " + target
|
||||
deleterSeed(t, ctx, fixture, stranger)
|
||||
|
||||
result := deleterDelete(t, ctx, fixture, publicops.DeleteRequest{
|
||||
IDs: []string{target},
|
||||
Force: true,
|
||||
Actor: "deleter-contract",
|
||||
})
|
||||
if result.ReferencesUpdated != 1 {
|
||||
t.Errorf("ReferencesUpdated = %d, want 1 — it counts ROWS, and one row was rewritten", result.ReferencesUpdated)
|
||||
}
|
||||
|
||||
marker := "[deleted:" + target + "]"
|
||||
for _, field := range []string{"description", "notes", "design", "acceptance_criteria"} {
|
||||
got := deleterText(t, ctx, fixture, neighbor.ID, field)
|
||||
if !strings.Contains(got, marker) {
|
||||
t.Errorf("neighbor %s = %q, want it to contain %q", field, got, marker)
|
||||
}
|
||||
if strings.Contains(got, "[deleted:"+lookalike+"]") {
|
||||
t.Errorf("neighbor %s = %q: the lookalike id was rewritten too", field, got)
|
||||
}
|
||||
}
|
||||
if got := deleterText(t, ctx, fixture, neighbor.ID, "notes"); !strings.Contains(got, lookalike) {
|
||||
t.Errorf("neighbor notes = %q, want the lookalike id %q intact", got, lookalike)
|
||||
}
|
||||
if got := deleterText(t, ctx, fixture, fixture.IssuePrefix+"-refs-stranger", "description"); strings.Contains(got, marker) {
|
||||
t.Errorf("a row with no edge to the deleted id was rewritten: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// RunDeleterDryRunChangesNothing pins the preview promise
|
||||
// (issueops/deleter.go, Deleter.Delete: "A DRY RUN CHANGES NOTHING"): the
|
||||
// preview reports the counts the real deletion goes on to report, rewrites
|
||||
// nothing, and leaves every row where it was.
|
||||
//
|
||||
// The two are compared against EACH OTHER rather than against literals, which
|
||||
// is the property a caller actually relies on — a preview whose number differs
|
||||
// from the run it precedes is worse than no preview.
|
||||
func RunDeleterDryRunChangesNothing(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
first := deleterSeedIssue(t, ctx, fixture, "dry", "1")
|
||||
second := deleterSeedIssue(t, ctx, fixture, "dry", "2")
|
||||
deleterAddEdge(t, ctx, fixture, second, first)
|
||||
|
||||
request := publicops.DeleteRequest{IDs: []string{first, second}, Actor: "deleter-contract"}
|
||||
preview := deleterDelete(t, ctx, fixture, deleterWithDryRun(request, true))
|
||||
if !preview.DryRun {
|
||||
t.Errorf("preview.DryRun = false, want the request echoed")
|
||||
}
|
||||
if preview.Deleted != 2 {
|
||||
t.Errorf("preview.Deleted = %d, want 2", preview.Deleted)
|
||||
}
|
||||
if preview.ReferencesUpdated != 0 {
|
||||
t.Errorf("preview.ReferencesUpdated = %d, want 0: a preview rewrites nothing", preview.ReferencesUpdated)
|
||||
}
|
||||
deleterAssertIssueRows(t, ctx, fixture, 2, first, second)
|
||||
|
||||
actual := deleterDelete(t, ctx, fixture, request)
|
||||
if actual.Deleted != preview.Deleted {
|
||||
t.Errorf("Deleted: preview said %d, the run said %d", preview.Deleted, actual.Deleted)
|
||||
}
|
||||
if actual.Dependencies != preview.Dependencies {
|
||||
t.Errorf("Dependencies: preview said %d, the run said %d", preview.Dependencies, actual.Dependencies)
|
||||
}
|
||||
if actual.Labels != preview.Labels || actual.Events != preview.Events {
|
||||
t.Errorf("Labels/Events: preview said %d/%d, the run said %d/%d",
|
||||
preview.Labels, preview.Events, actual.Labels, actual.Events)
|
||||
}
|
||||
deleterAssertIssueRows(t, ctx, fixture, 0, first, second)
|
||||
}
|
||||
|
||||
// RunDeleterRecordsAtMostOneHistoryEntry pins the versioning clause
|
||||
// (issueops/deleter.go, Deleter.Delete: "one call records AT MOST ONE entry").
|
||||
//
|
||||
// AT MOST, not exactly one: only the server-backed store records an entry at
|
||||
// all, so asserting exactly one would be asserting a property of one wiring.
|
||||
// The DRY RUN half is the sharp one — a preview that left a commit behind
|
||||
// would be a mutation wearing a preview's name.
|
||||
func RunDeleterRecordsAtMostOneHistoryEntry(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
if fixture.CountHistory == nil {
|
||||
t.Skip("this backend cannot observe history, so the entry-per-call clause is unobservable here")
|
||||
}
|
||||
first := deleterSeedIssue(t, ctx, fixture, "hist", "1")
|
||||
second := deleterSeedIssue(t, ctx, fixture, "hist", "2")
|
||||
request := publicops.DeleteRequest{IDs: []string{first, second}, Force: true}
|
||||
|
||||
before := deleterHistory(t, ctx, fixture)
|
||||
deleterDelete(t, ctx, fixture, deleterWithDryRun(request, true))
|
||||
if after := deleterHistory(t, ctx, fixture); after != before {
|
||||
t.Errorf("history went %d -> %d across a DRY RUN, want no entry at all", before, after)
|
||||
}
|
||||
|
||||
before = deleterHistory(t, ctx, fixture)
|
||||
deleterDelete(t, ctx, fixture, request)
|
||||
if after := deleterHistory(t, ctx, fixture); after < before || after > before+1 {
|
||||
t.Errorf("history went %d -> %d across one delete of 2 rows, want at most one more entry", before, after)
|
||||
}
|
||||
}
|
||||
|
||||
// RunDeleterDoesNotMutateTheCallerRequest pins the no-mutation promise
|
||||
// (issueops/deleter.go, DeleteRequest: "IDs is read, never written through, and
|
||||
// never sorted in place").
|
||||
//
|
||||
// It matters more here than on the roles whose requests are scalars: every
|
||||
// implementation NORMALIZES the id slice, and normalizing in place is the most
|
||||
// natural way to write that — it would hand the caller back a shorter, trimmed,
|
||||
// reordered version of the list it passed, which is the list a CLI then echoes
|
||||
// in its confirmation hint.
|
||||
func RunDeleterDoesNotMutateTheCallerRequest(t *testing.T, ctx context.Context, fixture DeleterFixture) {
|
||||
t.Helper()
|
||||
id := deleterSeedIssue(t, ctx, fixture, "immutable", "target")
|
||||
ids := []string{" " + id + " ", id, fixture.IssuePrefix + "-immutable-absent"}
|
||||
snapshot := append([]string(nil), ids...)
|
||||
|
||||
request := publicops.DeleteRequest{IDs: ids, Actor: "deleter-contract", Force: true, DryRun: true}
|
||||
requestSnapshot := request
|
||||
|
||||
// The absent id makes this a refusal, which is deliberate: a body that
|
||||
// normalizes in place does it BEFORE it discovers the request is doomed,
|
||||
// so the failing path is where the mutation would survive unnoticed.
|
||||
if _, err := fixture.Deleter.Delete(ctx, request); !errors.Is(err, publicops.ErrNotFound) {
|
||||
t.Fatalf("Delete() error = %v, want ErrNotFound", err)
|
||||
}
|
||||
if !reflect.DeepEqual(ids, snapshot) {
|
||||
t.Errorf("the caller's id slice changed across the call: got %v, want %v", ids, snapshot)
|
||||
}
|
||||
if !reflect.DeepEqual(request.IDs, requestSnapshot.IDs) {
|
||||
t.Errorf("the caller's request changed across the call: got %+v, want %+v", request, requestSnapshot)
|
||||
}
|
||||
}
|
||||
|
||||
// --- fixture helpers -------------------------------------------------------
|
||||
|
||||
func deleterIssue(fixture DeleterFixture, tag, name string, ephemeral bool) *types.Issue {
|
||||
return &types.Issue{
|
||||
ID: fmt.Sprintf("%s-%s-%s", fixture.IssuePrefix, tag, name),
|
||||
Title: tag + " " + name,
|
||||
Status: types.StatusOpen,
|
||||
Priority: 2,
|
||||
IssueType: types.TypeTask,
|
||||
Ephemeral: ephemeral,
|
||||
}
|
||||
}
|
||||
|
||||
// deleterSeed writes one issue through the plane its Ephemeral flag names.
|
||||
func deleterSeed(t *testing.T, ctx context.Context, fixture DeleterFixture, issue *types.Issue) string {
|
||||
t.Helper()
|
||||
create := fixture.CreateIssue
|
||||
if issue.Ephemeral {
|
||||
create = fixture.CreateWisp
|
||||
}
|
||||
if err := create(ctx, issue, "deleter-seed"); err != nil {
|
||||
t.Fatalf("seeding %s: %v", issue.ID, err)
|
||||
}
|
||||
return issue.ID
|
||||
}
|
||||
|
||||
func deleterSeedIssue(t *testing.T, ctx context.Context, fixture DeleterFixture, tag, name string) string {
|
||||
t.Helper()
|
||||
return deleterSeed(t, ctx, fixture, deleterIssue(fixture, tag, name, false))
|
||||
}
|
||||
|
||||
// deleterSeedWisp is its ephemeral sibling, used by the one case that is
|
||||
// about which PLANE a row lives in.
|
||||
func deleterSeedWisp(t *testing.T, ctx context.Context, fixture DeleterFixture, tag, name string) string {
|
||||
t.Helper()
|
||||
return deleterSeed(t, ctx, fixture, deleterIssue(fixture, tag, name, true))
|
||||
}
|
||||
|
||||
// deleterAddEdge makes dependent depend on blocker, which is what makes
|
||||
// dependent a DEPENDENT of blocker for this role's guard.
|
||||
func deleterAddEdge(t *testing.T, ctx context.Context, fixture DeleterFixture, dependent, blocker string) {
|
||||
t.Helper()
|
||||
err := fixture.AddDependency(ctx, &types.Dependency{
|
||||
IssueID: dependent,
|
||||
DependsOnID: blocker,
|
||||
Type: types.DepBlocks,
|
||||
}, "deleter-seed")
|
||||
if err != nil {
|
||||
t.Fatalf("seeding edge %s -> %s: %v", dependent, blocker, err)
|
||||
}
|
||||
}
|
||||
|
||||
func deleterWithDryRun(request publicops.DeleteRequest, dryRun bool) publicops.DeleteRequest {
|
||||
request.DryRun = dryRun
|
||||
return request
|
||||
}
|
||||
|
||||
func deleterDelete(t *testing.T, ctx context.Context, fixture DeleterFixture, request publicops.DeleteRequest) publicops.DeleteResult {
|
||||
t.Helper()
|
||||
result, err := fixture.Deleter.Delete(ctx, request)
|
||||
if err != nil {
|
||||
t.Fatalf("Delete(%+v) error = %v", request, err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// deleterAssertIssueRows counts the named ids in the ISSUES plane. It is the
|
||||
// assertion that does not trust the result the delete reported about itself,
|
||||
// which on a destructive operation is the one that matters.
|
||||
func deleterAssertIssueRows(t *testing.T, ctx context.Context, fixture DeleterFixture, want int, ids ...string) {
|
||||
t.Helper()
|
||||
placeholders := make([]string, len(ids))
|
||||
args := make([]any, len(ids))
|
||||
for i, id := range ids {
|
||||
placeholders[i] = "?"
|
||||
args[i] = id
|
||||
}
|
||||
var got int
|
||||
query := "SELECT COUNT(*) FROM issues WHERE id IN (" + strings.Join(placeholders, ",") + ")"
|
||||
if err := fixture.QueryScalar(ctx, query, args, &got); err != nil {
|
||||
t.Fatalf("counting issue rows for %v: %v", ids, err)
|
||||
}
|
||||
if got != want {
|
||||
t.Errorf("issue rows for %v = %d, want %d", ids, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// deleterAssertWispRows is deleterAssertIssueRows for the ephemeral plane.
|
||||
func deleterAssertWispRows(t *testing.T, ctx context.Context, fixture DeleterFixture, want int, ids ...string) {
|
||||
t.Helper()
|
||||
placeholders := make([]string, len(ids))
|
||||
args := make([]any, len(ids))
|
||||
for i, id := range ids {
|
||||
placeholders[i] = "?"
|
||||
args[i] = id
|
||||
}
|
||||
var got int
|
||||
query := "SELECT COUNT(*) FROM wisps WHERE id IN (" + strings.Join(placeholders, ",") + ")"
|
||||
if err := fixture.QueryScalar(ctx, query, args, &got); err != nil {
|
||||
t.Fatalf("counting wisp rows for %v: %v", ids, err)
|
||||
}
|
||||
if got != want {
|
||||
t.Errorf("wisp rows for %v = %d, want %d", ids, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// deleterAssertEdgeRows counts the stored edges from dependent to blocker.
|
||||
func deleterAssertEdgeRows(t *testing.T, ctx context.Context, fixture DeleterFixture, want int, dependent, blocker string) {
|
||||
t.Helper()
|
||||
var got int
|
||||
query := "SELECT COUNT(*) FROM dependencies WHERE issue_id = ? AND " +
|
||||
"COALESCE(depends_on_issue_id, depends_on_wisp_id, depends_on_external) = ?"
|
||||
if err := fixture.QueryScalar(ctx, query, []any{dependent, blocker}, &got); err != nil {
|
||||
t.Fatalf("counting edges %s -> %s: %v", dependent, blocker, err)
|
||||
}
|
||||
if got != want {
|
||||
t.Errorf("edges %s -> %s = %d, want %d", dependent, blocker, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// deleterText reads one long text column straight out of the issues table,
|
||||
// because the rewrite is a claim about stored bytes rather than about anything
|
||||
// the role reports.
|
||||
//
|
||||
//nolint:gosec // G201: column is chosen by the caller from a fixed set of four.
|
||||
func deleterText(t *testing.T, ctx context.Context, fixture DeleterFixture, id, column string) string {
|
||||
t.Helper()
|
||||
var got string
|
||||
query := fmt.Sprintf("SELECT COALESCE(%s, '') FROM issues WHERE id = ?", column)
|
||||
if err := fixture.QueryScalar(ctx, query, []any{id}, &got); err != nil {
|
||||
t.Fatalf("reading %s.%s: %v", id, column, err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
func deleterHistory(t *testing.T, ctx context.Context, fixture DeleterFixture) int {
|
||||
t.Helper()
|
||||
entries, err := fixture.CountHistory(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("CountHistory(): %v", err)
|
||||
}
|
||||
return entries
|
||||
}
|
||||
414
cmd/bd/delete.go
414
cmd/bd/delete.go
|
|
@ -5,14 +5,15 @@ import (
|
|||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/steveyegge/beads/internal/metrics"
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
storeissueops "github.com/steveyegge/beads/internal/storage/issueops"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
var deleteCmd = &cobra.Command{
|
||||
|
|
@ -37,7 +38,7 @@ Delete from file (one ID per line):
|
|||
Preview before deleting:
|
||||
bd delete --from-file deletions.txt --dry-run
|
||||
|
||||
DEPENDENCY HANDLING:
|
||||
DEPENDENCY HANDLING (the same on a local database and against a team server):
|
||||
Default: Fails if any issue has dependents not in deletion set
|
||||
bd delete bd-1 bd-2
|
||||
|
||||
|
|
@ -100,7 +101,10 @@ Force: Delete and orphan dependents
|
|||
|
||||
issueID := issueIDs[0]
|
||||
ctx := rootCtx
|
||||
// Get the issue to be deleted, using prefix-based routing
|
||||
// Get the issue to be deleted, using prefix-based routing. Resolution is
|
||||
// the FRONT DOOR'S job and stays here: issueops.DeleteRequest.IDs are
|
||||
// exact, because resolving an ambiguous prefix to a row and then deleting
|
||||
// it is the one place a convenience is not one.
|
||||
routedResult, err := resolveAndGetIssueForMutation(ctx, store, issueID)
|
||||
if err != nil {
|
||||
if isNotFoundErr(err) {
|
||||
|
|
@ -112,159 +116,161 @@ Force: Delete and orphan dependents
|
|||
issue := routedResult.Issue
|
||||
issueID = routedResult.ResolvedID
|
||||
activeStore := routedResult.Store
|
||||
connectedIssues := make(map[string]*types.Issue)
|
||||
deps, err := activeStore.GetDependencies(ctx, issueID)
|
||||
|
||||
deleter, err := activeStore.Deleter()
|
||||
if err != nil {
|
||||
return HandleError("getting dependencies: %v", err)
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
for _, dep := range deps {
|
||||
connectedIssues[dep.ID] = dep
|
||||
// --force is this command's CONFIRMATION as well as its orphan mode, so an
|
||||
// unconfirmed run asks the role the same question a --dry-run does.
|
||||
// Everything else is the request the user typed: the guard, the deletion
|
||||
// and the reference rewrite are all the role's, and none of them is
|
||||
// written here any more. This path used to hold its own transaction that
|
||||
// removed each edge by hand and rewrote the neighbors' text; the whole of
|
||||
// it is issueops.Deleter now, which is also what puts the rewrite INSIDE
|
||||
// the transaction that deletes.
|
||||
request := issueops.DeleteRequest{
|
||||
Actor: actor,
|
||||
IDs: []string{issueID},
|
||||
Force: force,
|
||||
DryRun: dryRun || !force,
|
||||
}
|
||||
dependents, err := activeStore.GetDependents(ctx, issueID)
|
||||
if err != nil {
|
||||
return HandleError("getting dependents: %v", err)
|
||||
}
|
||||
for _, dependent := range dependents {
|
||||
connectedIssues[dependent.ID] = dependent
|
||||
}
|
||||
depRecords, err := activeStore.GetDependencyRecords(ctx, issueID)
|
||||
if err != nil {
|
||||
return HandleError("getting dependency records: %v", err)
|
||||
}
|
||||
// Build the regex pattern for matching issue IDs (handles hyphenated IDs properly)
|
||||
// Pattern: (^|non-word-char)(issueID)($|non-word-char) where word-char includes hyphen
|
||||
idPattern := `(^|[^A-Za-z0-9_-])(` + regexp.QuoteMeta(issueID) + `)($|[^A-Za-z0-9_-])`
|
||||
re := regexp.MustCompile(idPattern)
|
||||
replacementText := `$1[deleted:` + issueID + `]$3`
|
||||
if dryRun || !force {
|
||||
var previewResult *types.DeleteIssuesResult
|
||||
if dryRun {
|
||||
previewResult, err = activeStore.DeleteIssues(ctx, []string{issueID}, false, force, true)
|
||||
if err != nil {
|
||||
if previewErr := outputDeletionPreview([]string{issueID}, map[string]*types.Issue{issueID: issue}, false, true, previewResult, err, jsonOutput); previewErr != nil {
|
||||
return previewErr
|
||||
}
|
||||
if jsonOutput {
|
||||
return outputJSONError(err, "")
|
||||
}
|
||||
return HandleError("previewing deletion: %v", err)
|
||||
result, err := deleter.Delete(ctx, request)
|
||||
if request.DryRun {
|
||||
if err != nil {
|
||||
if previewErr := outputDeletionPreview([]string{issueID}, map[string]*types.Issue{issueID: issue}, false, dryRun, nil, err, jsonOutput); previewErr != nil {
|
||||
return previewErr
|
||||
}
|
||||
if jsonOutput {
|
||||
return outputJSONError(err, "")
|
||||
}
|
||||
return HandleError("previewing deletion: %v", err)
|
||||
}
|
||||
if jsonOutput || isQuiet() {
|
||||
return outputDeletionPreview([]string{issueID}, map[string]*types.Issue{issueID: issue}, false, dryRun, previewResult, nil, jsonOutput)
|
||||
return outputDeletionPreview([]string{issueID}, map[string]*types.Issue{issueID: issue}, false, dryRun, &result, nil, jsonOutput)
|
||||
}
|
||||
fmt.Printf("\n%s\n", ui.RenderFail("⚠️ DELETE PREVIEW"))
|
||||
fmt.Printf("\nIssue to delete:\n")
|
||||
fmt.Printf(" %s: %s\n", issueID, issue.Title)
|
||||
totalDeps := len(depRecords) + len(dependents)
|
||||
if totalDeps > 0 {
|
||||
fmt.Printf("\nDependency links to remove: %d\n", totalDeps)
|
||||
for _, dep := range depRecords {
|
||||
fmt.Printf(" %s → %s (%s)\n", dep.IssueID, dep.DependsOnID, dep.Type)
|
||||
}
|
||||
for _, dep := range dependents {
|
||||
fmt.Printf(" %s → %s (inbound)\n", dep.ID, issueID)
|
||||
}
|
||||
}
|
||||
if len(connectedIssues) > 0 {
|
||||
fmt.Printf("\nConnected issues where text references will be updated:\n")
|
||||
issuesWithRefs := 0
|
||||
for id, connIssue := range connectedIssues {
|
||||
hasRefs := re.MatchString(connIssue.Description) ||
|
||||
(connIssue.Notes != "" && re.MatchString(connIssue.Notes)) ||
|
||||
(connIssue.Design != "" && re.MatchString(connIssue.Design)) ||
|
||||
(connIssue.AcceptanceCriteria != "" && re.MatchString(connIssue.AcceptanceCriteria))
|
||||
if hasRefs {
|
||||
fmt.Printf(" %s: %s\n", id, connIssue.Title)
|
||||
issuesWithRefs++
|
||||
}
|
||||
}
|
||||
if issuesWithRefs == 0 {
|
||||
fmt.Printf(" (none have text references)\n")
|
||||
}
|
||||
}
|
||||
if dryRun {
|
||||
fmt.Printf("\nWould delete: %d issues\n", previewResult.DeletedCount)
|
||||
fmt.Printf("Would remove: %d dependencies, %d labels, %d events\n", previewResult.DependenciesCount, previewResult.LabelsCount, previewResult.EventsCount)
|
||||
if len(previewResult.OrphanedIssues) > 0 {
|
||||
fmt.Printf("Would orphan: %d issues\n", len(previewResult.OrphanedIssues))
|
||||
}
|
||||
fmt.Printf("\n(Dry-run mode - no changes made)\n")
|
||||
} else {
|
||||
fmt.Printf("\n%s\n", ui.RenderWarn("This operation cannot be undone!"))
|
||||
fmt.Printf("To proceed, run: %s\n\n", ui.RenderWarn("bd delete "+issueID+" --force"))
|
||||
}
|
||||
return nil
|
||||
return renderSingleDeletePreview(ctx, activeStore, issueID, issue, dryRun, result)
|
||||
}
|
||||
updatedIssueCount := 0
|
||||
totalDepsRemoved := 0
|
||||
deleteErr := transactHonoringAutoCommit(ctx, activeStore, fmt.Sprintf("bd: delete %s", issueID), func(tx storage.Transaction) error {
|
||||
for id, connIssue := range connectedIssues {
|
||||
updates := make(map[string]interface{})
|
||||
if re.MatchString(connIssue.Description) {
|
||||
updates["description"] = re.ReplaceAllString(connIssue.Description, replacementText)
|
||||
}
|
||||
if connIssue.Notes != "" && re.MatchString(connIssue.Notes) {
|
||||
updates["notes"] = re.ReplaceAllString(connIssue.Notes, replacementText)
|
||||
}
|
||||
if connIssue.Design != "" && re.MatchString(connIssue.Design) {
|
||||
updates["design"] = re.ReplaceAllString(connIssue.Design, replacementText)
|
||||
}
|
||||
if connIssue.AcceptanceCriteria != "" && re.MatchString(connIssue.AcceptanceCriteria) {
|
||||
updates["acceptance_criteria"] = re.ReplaceAllString(connIssue.AcceptanceCriteria, replacementText)
|
||||
}
|
||||
if len(updates) > 0 {
|
||||
if err := tx.UpdateIssue(ctx, id, updates, actor); err != nil {
|
||||
return fmt.Errorf("update references in %s: %w", id, err)
|
||||
}
|
||||
updatedIssueCount++
|
||||
}
|
||||
}
|
||||
for _, dep := range depRecords {
|
||||
if err := tx.RemoveDependency(ctx, dep.IssueID, dep.DependsOnID, actor); err != nil {
|
||||
return fmt.Errorf("remove dependency %s → %s: %w", dep.IssueID, dep.DependsOnID, err)
|
||||
}
|
||||
totalDepsRemoved++
|
||||
}
|
||||
for _, dep := range dependents {
|
||||
if err := tx.RemoveDependency(ctx, dep.ID, issueID, actor); err != nil {
|
||||
return fmt.Errorf("remove dependency %s → %s: %w", dep.ID, issueID, err)
|
||||
}
|
||||
totalDepsRemoved++
|
||||
}
|
||||
if err := tx.DeleteIssue(ctx, issueID); err != nil {
|
||||
return fmt.Errorf("delete %s: %w", issueID, err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if deleteErr != nil {
|
||||
return HandleError("deleting issue: %v", deleteErr)
|
||||
if err != nil {
|
||||
return HandleError("deleting issue: %v", err)
|
||||
}
|
||||
|
||||
commandDidWrite.Store(true)
|
||||
|
||||
if jsonOutput {
|
||||
// The single-issue keys, unchanged: `deleted` is the id rather than a
|
||||
// list here, and this is the shape every `bd delete <one-id> --json`
|
||||
// consumer already parses.
|
||||
if err := outputJSON(map[string]interface{}{
|
||||
"deleted": issueID,
|
||||
"dependencies_removed": totalDepsRemoved,
|
||||
"references_updated": updatedIssueCount,
|
||||
"dependencies_removed": result.Dependencies,
|
||||
"references_updated": result.ReferencesUpdated,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("%s Deleted %s\n", ui.RenderPass("✓"), issueID)
|
||||
fmt.Printf(" Removed %d dependency link(s)\n", totalDepsRemoved)
|
||||
fmt.Printf(" Updated text references in %d issue(s)\n", updatedIssueCount)
|
||||
fmt.Printf(" Removed %d dependency link(s)\n", result.Dependencies)
|
||||
fmt.Printf(" Updated text references in %d issue(s)\n", result.ReferencesUpdated)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
// renderSingleDeletePreview prints the human preview for a one-issue delete.
|
||||
//
|
||||
// It is PRESENTATION ONLY. The counts come from the role's dry run; the edge
|
||||
// listing and the "which neighbors cite this id" lines are reads this handler
|
||||
// makes to say WHICH links and WHICH issues, which no result carries and which
|
||||
// the role deliberately does not return - a delete answers with an effect, not
|
||||
// with rows.
|
||||
func renderSingleDeletePreview(
|
||||
ctx context.Context, activeStore storage.DoltStorage,
|
||||
issueID string, issue *types.Issue, dryRun bool, result issueops.DeleteResult,
|
||||
) error {
|
||||
connectedIssues := make(map[string]*types.Issue)
|
||||
deps, err := activeStore.GetDependencies(ctx, issueID)
|
||||
if err != nil {
|
||||
return HandleError("getting dependencies: %v", err)
|
||||
}
|
||||
for _, dep := range deps {
|
||||
connectedIssues[dep.ID] = dep
|
||||
}
|
||||
dependents, err := activeStore.GetDependents(ctx, issueID)
|
||||
if err != nil {
|
||||
return HandleError("getting dependents: %v", err)
|
||||
}
|
||||
for _, dependent := range dependents {
|
||||
connectedIssues[dependent.ID] = dependent
|
||||
}
|
||||
depRecords, err := activeStore.GetDependencyRecords(ctx, issueID)
|
||||
if err != nil {
|
||||
return HandleError("getting dependency records: %v", err)
|
||||
}
|
||||
// The role's own citation rule, not a second copy of it: a preview that
|
||||
// named a different set of neighbors than the deletion rewrites would be
|
||||
// worse than no preview.
|
||||
re := storeissueops.DeletedReferencePattern(issueID)
|
||||
|
||||
fmt.Printf("\n%s\n", ui.RenderFail("⚠️ DELETE PREVIEW"))
|
||||
fmt.Printf("\nIssue to delete:\n")
|
||||
fmt.Printf(" %s: %s\n", issueID, issue.Title)
|
||||
totalDeps := len(depRecords) + len(dependents)
|
||||
if totalDeps > 0 {
|
||||
fmt.Printf("\nDependency links to remove: %d\n", totalDeps)
|
||||
for _, dep := range depRecords {
|
||||
fmt.Printf(" %s → %s (%s)\n", dep.IssueID, dep.DependsOnID, dep.Type)
|
||||
}
|
||||
for _, dep := range dependents {
|
||||
fmt.Printf(" %s → %s (inbound)\n", dep.ID, issueID)
|
||||
}
|
||||
}
|
||||
if len(connectedIssues) > 0 {
|
||||
fmt.Printf("\nConnected issues where text references will be updated:\n")
|
||||
issuesWithRefs := 0
|
||||
for id, connIssue := range connectedIssues {
|
||||
hasRefs := re.MatchString(connIssue.Description) ||
|
||||
(connIssue.Notes != "" && re.MatchString(connIssue.Notes)) ||
|
||||
(connIssue.Design != "" && re.MatchString(connIssue.Design)) ||
|
||||
(connIssue.AcceptanceCriteria != "" && re.MatchString(connIssue.AcceptanceCriteria))
|
||||
if hasRefs {
|
||||
fmt.Printf(" %s: %s\n", id, connIssue.Title)
|
||||
issuesWithRefs++
|
||||
}
|
||||
}
|
||||
if issuesWithRefs == 0 {
|
||||
fmt.Printf(" (none have text references)\n")
|
||||
}
|
||||
}
|
||||
if dryRun {
|
||||
fmt.Printf("\nWould delete: %d issues\n", result.Deleted)
|
||||
fmt.Printf("Would remove: %d dependencies, %d labels, %d events\n", result.Dependencies, result.Labels, result.Events)
|
||||
if len(result.Orphaned) > 0 {
|
||||
fmt.Printf("Would orphan: %d issues\n", len(result.Orphaned))
|
||||
}
|
||||
fmt.Printf("\n(Dry-run mode - no changes made)\n")
|
||||
} else {
|
||||
fmt.Printf("\n%s\n", ui.RenderWarn("This operation cannot be undone!"))
|
||||
fmt.Printf("To proceed, run: %s\n\n", ui.RenderWarn("bd delete "+issueID+" --force"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// deleteIssue removes an issue from the database.
|
||||
func deleteIssue(ctx context.Context, issueID string) error {
|
||||
return store.DeleteIssue(ctx, issueID)
|
||||
}
|
||||
|
||||
// deleteBatch is the multi-id and cascade path, shared by `bd delete`,
|
||||
// `bd cleanup`, `bd wisp gc` and `bd mol burn`.
|
||||
//
|
||||
// It resolves the ids the way this front door always has - prefix matching and
|
||||
// cross-repository routing, which issueops.DeleteRequest deliberately does not
|
||||
// do - and then hands the RESOLVED ids to the role. Everything below that line
|
||||
// used to live here: the orphan guard, the cascade expansion, the deletion, and
|
||||
// a text-reference rewrite that ran OUTSIDE the delete transaction and threw
|
||||
// away every update error it got.
|
||||
//
|
||||
//nolint:unparam // cmd parameter required for potential future use
|
||||
func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, cascade bool, jsonOutput bool, _ bool, _ ...string) error {
|
||||
if store == nil {
|
||||
|
|
@ -274,6 +280,7 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c
|
|||
}
|
||||
ctx := rootCtx
|
||||
issues := make(map[string]*types.Issue)
|
||||
resolvedIDs := make([]string, 0, len(issueIDs))
|
||||
notFound := []string{}
|
||||
var routedStore storage.DoltStorage
|
||||
for _, id := range issueIDs {
|
||||
|
|
@ -286,6 +293,7 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c
|
|||
}
|
||||
} else {
|
||||
issues[result.ResolvedID] = result.Issue
|
||||
resolvedIDs = append(resolvedIDs, result.ResolvedID)
|
||||
if result.Routed && routedStore == nil {
|
||||
routedStore = result.Store
|
||||
} else {
|
||||
|
|
@ -303,10 +311,24 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c
|
|||
if routedStore != nil {
|
||||
batchStore = routedStore
|
||||
}
|
||||
if dryRun || !force {
|
||||
result, err := batchStore.DeleteIssues(ctx, issueIDs, cascade, force, true)
|
||||
|
||||
deleter, err := batchStore.Deleter()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// --force is the confirmation as well as the orphan mode, so an unconfirmed
|
||||
// run asks the role what it WOULD do; see the single-id path.
|
||||
request := issueops.DeleteRequest{
|
||||
Actor: actor,
|
||||
IDs: resolvedIDs,
|
||||
Cascade: cascade,
|
||||
Force: force,
|
||||
DryRun: dryRun || !force,
|
||||
}
|
||||
result, err := deleter.Delete(ctx, request)
|
||||
if request.DryRun {
|
||||
if err != nil {
|
||||
if previewErr := outputDeletionPreview(issueIDs, issues, cascade, dryRun, result, err, jsonOutput); previewErr != nil {
|
||||
if previewErr := outputDeletionPreview(resolvedIDs, issues, cascade, dryRun, nil, err, jsonOutput); previewErr != nil {
|
||||
return previewErr
|
||||
}
|
||||
if jsonOutput {
|
||||
|
|
@ -314,82 +336,60 @@ func deleteBatch(_ *cobra.Command, issueIDs []string, force bool, dryRun bool, c
|
|||
}
|
||||
return err
|
||||
}
|
||||
if previewErr := outputDeletionPreview(issueIDs, issues, cascade, dryRun, result, nil, jsonOutput); previewErr != nil {
|
||||
if previewErr := outputDeletionPreview(resolvedIDs, issues, cascade, dryRun, &result, nil, jsonOutput); previewErr != nil {
|
||||
return previewErr
|
||||
}
|
||||
if !dryRun && !jsonOutput && !isQuiet() {
|
||||
fmt.Printf("\n%s\n", ui.RenderWarn("This operation cannot be undone!"))
|
||||
if cascade {
|
||||
fmt.Printf("To proceed with cascade deletion, run: %s\n",
|
||||
ui.RenderWarn("bd delete "+strings.Join(issueIDs, " ")+" --cascade --force"))
|
||||
ui.RenderWarn("bd delete "+strings.Join(resolvedIDs, " ")+" --cascade --force"))
|
||||
} else {
|
||||
fmt.Printf("To proceed, run: %s\n",
|
||||
ui.RenderWarn("bd delete "+strings.Join(issueIDs, " ")+" --force"))
|
||||
ui.RenderWarn("bd delete "+strings.Join(resolvedIDs, " ")+" --force"))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
connectedIssues := make(map[string]*types.Issue)
|
||||
idSet := make(map[string]bool)
|
||||
for _, id := range issueIDs {
|
||||
idSet[id] = true
|
||||
}
|
||||
for _, id := range issueIDs {
|
||||
deps, err := batchStore.GetDependencies(ctx, id)
|
||||
if err == nil {
|
||||
for _, dep := range deps {
|
||||
if !idSet[dep.ID] {
|
||||
connectedIssues[dep.ID] = dep
|
||||
}
|
||||
}
|
||||
}
|
||||
dependents, err := batchStore.GetDependents(ctx, id)
|
||||
if err == nil {
|
||||
for _, dep := range dependents {
|
||||
if !idSet[dep.ID] {
|
||||
connectedIssues[dep.ID] = dep
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
result, err := batchStore.DeleteIssues(ctx, issueIDs, cascade, force, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
updatedCount := updateTextReferencesInIssues(ctx, issueIDs, connectedIssues)
|
||||
|
||||
commandDidWrite.Store(true)
|
||||
|
||||
if jsonOutput {
|
||||
if err := outputJSON(map[string]interface{}{
|
||||
"deleted": issueIDs,
|
||||
"deleted_count": result.DeletedCount,
|
||||
"dependencies_removed": result.DependenciesCount,
|
||||
"labels_removed": result.LabelsCount,
|
||||
"events_removed": result.EventsCount,
|
||||
"references_updated": updatedCount,
|
||||
"orphaned_issues": result.OrphanedIssues,
|
||||
"deleted": resolvedIDs,
|
||||
"deleted_count": result.Deleted,
|
||||
"dependencies_removed": result.Dependencies,
|
||||
"labels_removed": result.Labels,
|
||||
"events_removed": result.Events,
|
||||
"references_updated": result.ReferencesUpdated,
|
||||
"orphaned_issues": result.Orphaned,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("%s Deleted %d issue(s)\n", ui.RenderPass("✓"), result.DeletedCount)
|
||||
fmt.Printf(" Removed %d dependency link(s)\n", result.DependenciesCount)
|
||||
fmt.Printf(" Removed %d label(s)\n", result.LabelsCount)
|
||||
fmt.Printf(" Removed %d event(s)\n", result.EventsCount)
|
||||
fmt.Printf(" Updated text references in %d issue(s)\n", updatedCount)
|
||||
if len(result.OrphanedIssues) > 0 {
|
||||
fmt.Printf("%s Deleted %d issue(s)\n", ui.RenderPass("✓"), result.Deleted)
|
||||
fmt.Printf(" Removed %d dependency link(s)\n", result.Dependencies)
|
||||
fmt.Printf(" Removed %d label(s)\n", result.Labels)
|
||||
fmt.Printf(" Removed %d event(s)\n", result.Events)
|
||||
fmt.Printf(" Updated text references in %d issue(s)\n", result.ReferencesUpdated)
|
||||
if len(result.Orphaned) > 0 {
|
||||
fmt.Printf(" %s Orphaned %d issue(s): %s\n",
|
||||
ui.RenderWarn("⚠"), len(result.OrphanedIssues), strings.Join(result.OrphanedIssues, ", "))
|
||||
ui.RenderWarn("⚠"), len(result.Orphaned), strings.Join(result.Orphaned, ", "))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// outputDeletionPreview renders a deletion preview without exposing issue payloads
|
||||
// in machine-readable or quiet output.
|
||||
func outputDeletionPreview(issueIDs []string, issues map[string]*types.Issue, cascade bool, dryRun bool, result *types.DeleteIssuesResult, depError error, jsonOutput bool) error {
|
||||
// outputDeletionPreview renders a deletion preview without exposing issue
|
||||
// payloads in machine-readable or quiet output.
|
||||
//
|
||||
// result is the ROLE's dry run, or nil when the role refused - a refusal has
|
||||
// no counts, and printing zeros beside the refusal would read as "nothing
|
||||
// would have been deleted" rather than "we did not get that far".
|
||||
func outputDeletionPreview(issueIDs []string, issues map[string]*types.Issue, cascade bool, dryRun bool, result *issueops.DeleteResult, depError error, jsonOutput bool) error {
|
||||
if jsonOutput {
|
||||
preview := map[string]interface{}{
|
||||
"preview": true,
|
||||
|
|
@ -398,11 +398,11 @@ func outputDeletionPreview(issueIDs []string, issues map[string]*types.Issue, ca
|
|||
"cascade": cascade,
|
||||
}
|
||||
if result != nil {
|
||||
preview["would_delete"] = result.DeletedCount
|
||||
preview["would_remove_dependencies"] = result.DependenciesCount
|
||||
preview["would_remove_labels"] = result.LabelsCount
|
||||
preview["would_remove_events"] = result.EventsCount
|
||||
preview["would_orphan"] = len(result.OrphanedIssues)
|
||||
preview["would_delete"] = result.Deleted
|
||||
preview["would_remove_dependencies"] = result.Dependencies
|
||||
preview["would_remove_labels"] = result.Labels
|
||||
preview["would_remove_events"] = result.Events
|
||||
preview["would_orphan"] = len(result.Orphaned)
|
||||
}
|
||||
if depError != nil {
|
||||
preview["error"] = depError.Error()
|
||||
|
|
@ -427,11 +427,11 @@ func outputDeletionPreview(issueIDs []string, issues map[string]*types.Issue, ca
|
|||
fmt.Printf("\n%s\n", ui.RenderFail(depError.Error()))
|
||||
}
|
||||
if result != nil {
|
||||
fmt.Printf("\nWould delete: %d issues\n", result.DeletedCount)
|
||||
fmt.Printf("\nWould delete: %d issues\n", result.Deleted)
|
||||
fmt.Printf("Would remove: %d dependencies, %d labels, %d events\n",
|
||||
result.DependenciesCount, result.LabelsCount, result.EventsCount)
|
||||
if len(result.OrphanedIssues) > 0 {
|
||||
fmt.Printf("Would orphan: %d issues\n", len(result.OrphanedIssues))
|
||||
result.Dependencies, result.Labels, result.Events)
|
||||
if len(result.Orphaned) > 0 {
|
||||
fmt.Printf("Would orphan: %d issues\n", len(result.Orphaned))
|
||||
}
|
||||
if dryRun {
|
||||
fmt.Printf("\n(Dry-run mode - no changes made)\n")
|
||||
|
|
@ -440,52 +440,6 @@ func outputDeletionPreview(issueIDs []string, issues map[string]*types.Issue, ca
|
|||
return nil
|
||||
}
|
||||
|
||||
// updateTextReferencesInIssues updates text references to deleted issues in pre-collected connected issues
|
||||
func updateTextReferencesInIssues(ctx context.Context, deletedIDs []string, connectedIssues map[string]*types.Issue) int {
|
||||
updatedCount := 0
|
||||
// For each deleted issue, update references in all connected issues
|
||||
for _, id := range deletedIDs {
|
||||
// Build regex pattern
|
||||
idPattern := `(^|[^A-Za-z0-9_-])(` + regexp.QuoteMeta(id) + `)($|[^A-Za-z0-9_-])`
|
||||
re := regexp.MustCompile(idPattern)
|
||||
replacementText := `$1[deleted:` + id + `]$3`
|
||||
for connID, connIssue := range connectedIssues {
|
||||
updates := make(map[string]interface{})
|
||||
if re.MatchString(connIssue.Description) {
|
||||
updates["description"] = re.ReplaceAllString(connIssue.Description, replacementText)
|
||||
}
|
||||
if connIssue.Notes != "" && re.MatchString(connIssue.Notes) {
|
||||
updates["notes"] = re.ReplaceAllString(connIssue.Notes, replacementText)
|
||||
}
|
||||
if connIssue.Design != "" && re.MatchString(connIssue.Design) {
|
||||
updates["design"] = re.ReplaceAllString(connIssue.Design, replacementText)
|
||||
}
|
||||
if connIssue.AcceptanceCriteria != "" && re.MatchString(connIssue.AcceptanceCriteria) {
|
||||
updates["acceptance_criteria"] = re.ReplaceAllString(connIssue.AcceptanceCriteria, replacementText)
|
||||
}
|
||||
if len(updates) > 0 {
|
||||
if err := store.UpdateIssue(ctx, connID, updates, actor); err == nil {
|
||||
updatedCount++
|
||||
// Update the in-memory issue to avoid double-replacing
|
||||
if desc, ok := updates["description"].(string); ok {
|
||||
connIssue.Description = desc
|
||||
}
|
||||
if notes, ok := updates["notes"].(string); ok {
|
||||
connIssue.Notes = notes
|
||||
}
|
||||
if design, ok := updates["design"].(string); ok {
|
||||
connIssue.Design = design
|
||||
}
|
||||
if ac, ok := updates["acceptance_criteria"].(string); ok {
|
||||
connIssue.AcceptanceCriteria = ac
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return updatedCount
|
||||
}
|
||||
|
||||
// readIssueIDsFromFile reads issue IDs from a file (one per line)
|
||||
func readIssueIDsFromFile(filename string) ([]string, error) {
|
||||
// #nosec G304 - user-provided file path is intentional
|
||||
|
|
|
|||
|
|
@ -81,19 +81,44 @@ func TestEmbeddedDelete(t *testing.T) {
|
|||
})
|
||||
|
||||
t.Run("delete_without_force_shows_preview", func(t *testing.T) {
|
||||
target := bdCreate(t, bd, dir, "Lonely", "--type", "task")
|
||||
|
||||
// Without --force, bd delete shows a preview (exits 0) but does not delete.
|
||||
out := bdDelete(t, bd, dir, target.ID)
|
||||
if !strings.Contains(out, "PREVIEW") && !strings.Contains(out, "preview") {
|
||||
t.Logf("expected preview output: %s", out)
|
||||
}
|
||||
got := bdShow(t, bd, dir, target.ID)
|
||||
if got.ID != target.ID {
|
||||
t.Errorf("expected the target to still exist after preview")
|
||||
}
|
||||
})
|
||||
|
||||
// The one-id preview over a bead with an OUTSIDE dependent now refuses
|
||||
// rather than exiting 0, which is a change and is the direct route
|
||||
// converging with itself: the batch path and `--dry-run` have always
|
||||
// refused here (see TestEmbeddedDeleteJSONDependencyErrorContract, which
|
||||
// runs both), and only the unconfirmed single-id preview did not. The
|
||||
// refusal is the role's, so both routes and all three of this command's
|
||||
// paths now give the same answer to the same question.
|
||||
t.Run("delete_without_force_refuses_over_an_outside_dependent", func(t *testing.T) {
|
||||
parent := bdCreate(t, bd, dir, "Parent strict", "--type", "task")
|
||||
child := bdCreate(t, bd, dir, "Child strict", "--type", "task")
|
||||
bdDepAdd(t, bd, dir, child.ID, parent.ID)
|
||||
|
||||
// Without --force, bd delete shows a preview (exits 0) but does not delete.
|
||||
out := bdDelete(t, bd, dir, parent.ID)
|
||||
if !strings.Contains(out, "PREVIEW") && !strings.Contains(out, "preview") {
|
||||
t.Logf("expected preview output: %s", out)
|
||||
out := bdDeleteFail(t, bd, dir, parent.ID)
|
||||
if !strings.Contains(out, "dependents not in deletion set") {
|
||||
t.Errorf("refusal did not name the guard: %s", out)
|
||||
}
|
||||
// Parent should still exist.
|
||||
got := bdShow(t, bd, dir, parent.ID)
|
||||
if got.ID != parent.ID {
|
||||
t.Errorf("expected parent to still exist after preview")
|
||||
if !strings.Contains(out, "--cascade") || !strings.Contains(out, "--force") {
|
||||
t.Errorf("refusal did not say what to send instead: %s", out)
|
||||
}
|
||||
// Nothing was deleted, on either end of the edge.
|
||||
if got := bdShow(t, bd, dir, parent.ID); got.ID != parent.ID {
|
||||
t.Errorf("expected the parent to survive a refused delete")
|
||||
}
|
||||
if got := bdShow(t, bd, dir, child.ID); got.ID != child.ID {
|
||||
t.Errorf("expected the dependent to survive a refused delete")
|
||||
}
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -122,15 +122,23 @@ func TestGatherDeleteInput(t *testing.T) {
|
|||
}
|
||||
})
|
||||
|
||||
t.Run("rejects cascade without accessing a store", func(t *testing.T) {
|
||||
// --cascade used to be REFUSED here ("delete always cascades"), which meant
|
||||
// a team server had no way to delete an issue without taking its
|
||||
// dependents. It is an opt-in now, the same as on the direct route.
|
||||
t.Run("accepts cascade as an opt-in", func(t *testing.T) {
|
||||
cmd := newCommand(t)
|
||||
if err := cmd.Flags().Set("cascade", "true"); err != nil {
|
||||
t.Fatalf("set cascade: %v", err)
|
||||
}
|
||||
jsonOutput, quietFlag = false, false
|
||||
|
||||
_, err := gatherDeleteInput(cmd, []string{"bd-target"})
|
||||
if err == nil || !strings.Contains(err.Error(), "--cascade") {
|
||||
t.Fatalf("gatherDeleteInput() error = %v, want --cascade rejection", err)
|
||||
got, err := gatherDeleteInput(cmd, []string{"bd-target"})
|
||||
if err != nil {
|
||||
t.Fatalf("gatherDeleteInput() error = %v, want nil", err)
|
||||
}
|
||||
want := &deleteInput{ids: []string{"bd-target"}, cascade: true}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("gatherDeleteInput(): got %#v, want %#v", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,13 @@ import (
|
|||
"testing"
|
||||
)
|
||||
|
||||
// TestProxiedServerDelete pins the CONVERGED semantics on a team server.
|
||||
//
|
||||
// This route used to hardcode cascade at both of its call sites and refuse the
|
||||
// --cascade flag outright, so `bd delete X --force` deleted X's whole subtree
|
||||
// and there was no way to ask for anything else. The three modes below are the
|
||||
// direct route's, unchanged, and this test is what says so from the far side
|
||||
// of a real Dolt sql-server.
|
||||
func TestProxiedServerDelete(t *testing.T) {
|
||||
requireSharedProxiedServer(t)
|
||||
t.Parallel()
|
||||
|
|
@ -30,7 +37,19 @@ func TestProxiedServerDelete(t *testing.T) {
|
|||
t.Fatalf("read HEAD before preview: %v", err)
|
||||
}
|
||||
|
||||
preview := bdProxiedDeleteJSON(t, bd, p.dir, "--json", target.ID)
|
||||
// MODE 1, and the change: an unqualified delete of a bead with a dependent
|
||||
// is REFUSED here now. It used to preview a cascade.
|
||||
refused := bdProxiedDeleteFail(t, bd, p.dir, target.ID)
|
||||
if !strings.Contains(refused, "dependents not in deletion set") {
|
||||
t.Errorf("unqualified delete: got %q, want the dependents guard", refused)
|
||||
}
|
||||
for _, id := range []string{survivor.ID, target.ID, dependent.ID, descendant.ID} {
|
||||
assertRowExists(t, db, "issues", id)
|
||||
}
|
||||
|
||||
// MODE 2: --cascade previews the closure, which is what this route used to
|
||||
// do without being asked.
|
||||
preview := bdProxiedDeleteJSON(t, bd, p.dir, "--json", "--cascade", target.ID)
|
||||
previewWant := map[string]any{
|
||||
"schema_version": float64(1),
|
||||
"would_delete": float64(3),
|
||||
|
|
@ -56,7 +75,8 @@ func TestProxiedServerDelete(t *testing.T) {
|
|||
t.Errorf("preview advanced HEAD: before=%s after=%s", headBefore, headAfterPreview)
|
||||
}
|
||||
|
||||
deleted := bdProxiedDeleteJSON(t, bd, p.dir, "--json", target.ID, "--force")
|
||||
// MODE 3: --cascade --force is the old `--force`, spelled.
|
||||
deleted := bdProxiedDeleteJSON(t, bd, p.dir, "--json", "--cascade", "--force", target.ID)
|
||||
deletedWant := map[string]any{
|
||||
"schema_version": float64(1),
|
||||
"deleted": []any{target.ID},
|
||||
|
|
@ -65,6 +85,8 @@ func TestProxiedServerDelete(t *testing.T) {
|
|||
"labels_removed": float64(1),
|
||||
"events_removed": float64(4),
|
||||
"references_updated": float64(1),
|
||||
// A cascade leaves nothing outside the set to orphan.
|
||||
"orphaned_issues": nil,
|
||||
}
|
||||
if !deleteJSONEqual(deleted, deletedWant) {
|
||||
t.Errorf("delete JSON: got %#v, want %#v", deleted, deletedWant)
|
||||
|
|
@ -113,6 +135,41 @@ func TestProxiedServerDelete(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// TestProxiedServerDeleteForceOrphans is the mode this route could not express
|
||||
// at all before: --force without --cascade deletes the NAMED bead and leaves
|
||||
// its dependent standing. A team-server script that relied on the implicit
|
||||
// cascade gets orphans here instead of a deleted subtree, which is the
|
||||
// user-visible half of the convergence.
|
||||
func TestProxiedServerDeleteForceOrphans(t *testing.T) {
|
||||
requireSharedProxiedServer(t)
|
||||
t.Parallel()
|
||||
bd := buildEmbeddedBD(t)
|
||||
p := newSharedProxiedProject(t, bd, "delorph")
|
||||
|
||||
blocker := bdProxiedCreate(t, bd, p.dir, "Blocker", "--type", "task")
|
||||
dependent := bdProxiedCreate(t, bd, p.dir, "Dependent", "--type", "task", "--deps", "depends-on:"+blocker.ID)
|
||||
|
||||
db := openProxiedDB(t, p)
|
||||
deleted := bdProxiedDeleteJSON(t, bd, p.dir, "--json", "--force", blocker.ID)
|
||||
if got := deleted["deleted_count"]; got != float64(1) {
|
||||
t.Errorf("deleted_count = %v, want 1: --force deletes the NAMED bead and orphans the rest", got)
|
||||
}
|
||||
if got := deleted["orphaned_issues"]; !reflect.DeepEqual(got, []any{dependent.ID}) {
|
||||
t.Errorf("orphaned_issues = %#v, want [%s]", got, dependent.ID)
|
||||
}
|
||||
assertRowAbsent(t, db, "issues", blocker.ID)
|
||||
assertRowExists(t, db, "issues", dependent.ID)
|
||||
|
||||
var edges int
|
||||
if err := db.QueryRowContext(context.Background(),
|
||||
"SELECT COUNT(*) FROM dependencies WHERE issue_id = ?", dependent.ID).Scan(&edges); err != nil {
|
||||
t.Fatalf("count orphan edges: %v", err)
|
||||
}
|
||||
if edges != 0 {
|
||||
t.Errorf("orphan kept %d edge(s) into the deleted bead, want 0", edges)
|
||||
}
|
||||
}
|
||||
|
||||
func deleteJSONEqual(got, want map[string]any) bool {
|
||||
return reflect.DeepEqual(got, want)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,21 +11,19 @@ import (
|
|||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
"github.com/steveyegge/beads/internal/storage/uow"
|
||||
"github.com/steveyegge/beads/internal/ui"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
type deleteInput struct {
|
||||
ids []string
|
||||
force bool
|
||||
dryRun bool
|
||||
cascade bool
|
||||
jsonOutput bool
|
||||
quiet bool
|
||||
}
|
||||
|
||||
func gatherDeleteInput(cmd *cobra.Command, args []string) (*deleteInput, error) {
|
||||
if cmd.Flags().Changed("cascade") {
|
||||
return nil, fmt.Errorf("--cascade is not supported in proxied-server mode (delete always cascades)")
|
||||
}
|
||||
|
||||
in := &deleteInput{}
|
||||
in.ids = append(in.ids, args...)
|
||||
|
||||
|
|
@ -40,11 +38,40 @@ func gatherDeleteInput(cmd *cobra.Command, args []string) (*deleteInput, error)
|
|||
|
||||
in.force, _ = cmd.Flags().GetBool("force")
|
||||
in.dryRun, _ = cmd.Flags().GetBool("dry-run")
|
||||
// --cascade IS SUPPORTED HERE NOW. This route used to refuse the flag
|
||||
// outright ("delete always cascades") and hardcode Cascade: true at both of
|
||||
// its call sites, so on a team server there was no way to delete an issue
|
||||
// without taking its dependents and asking for the safer behavior was an
|
||||
// error. Both routes now mean the same three things by the same two flags.
|
||||
in.cascade, _ = cmd.Flags().GetBool("cascade")
|
||||
in.jsonOutput = jsonOutput
|
||||
in.quiet = isQuiet()
|
||||
return in, nil
|
||||
}
|
||||
|
||||
// proxiedDeleter hands back the named-row erasure surface for the proxied
|
||||
// route, through the provider's OWN capability accessor rather than a
|
||||
// constructor — the accessor is where a decorator would add its layer.
|
||||
func proxiedDeleter() (issueops.Deleter, error) {
|
||||
if uowProvider == nil {
|
||||
return nil, fmt.Errorf("proxied-server UOW provider not initialized")
|
||||
}
|
||||
source, ok := uowProvider.(uow.DeleterSource)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("proxied-server provider %T does not offer the Deleter accessor", uowProvider)
|
||||
}
|
||||
return source.Deleter()
|
||||
}
|
||||
|
||||
// runDeleteProxiedServer is `bd delete` against a team server.
|
||||
//
|
||||
// WHAT IT NO LONGER DOES is most of what it used to. It held its own copy of
|
||||
// the whole flow — a preview unit of work, a committing unit of work, its own
|
||||
// not-found check, and Cascade hardcoded true at both call sites — and the two
|
||||
// routes disagreed about what `--force` MEANS on a destructive command. The
|
||||
// selection, the guard and the deletion are issueops.Deleter now, the same
|
||||
// library surface the direct route calls; what is left here is this route's
|
||||
// output, which is not the direct route's and is pinned separately.
|
||||
func runDeleteProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error {
|
||||
in, err := gatherDeleteInput(cmd, args)
|
||||
if err != nil {
|
||||
|
|
@ -55,80 +82,57 @@ func runDeleteProxiedServer(cmd *cobra.Command, ctx context.Context, args []stri
|
|||
return HandleError("no issue IDs provided")
|
||||
}
|
||||
|
||||
if uowProvider == nil {
|
||||
return HandleError("proxied-server UOW provider not initialized")
|
||||
deleter, err := proxiedDeleter()
|
||||
if err != nil {
|
||||
return HandleError("%v", err)
|
||||
}
|
||||
|
||||
if in.dryRun || !in.force {
|
||||
return runDeleteProxiedPreviewTx(ctx, in)
|
||||
// --force is the confirmation as well as the orphan mode, exactly as on the
|
||||
// direct route, so an unconfirmed run asks the role what it WOULD do.
|
||||
request := issueops.DeleteRequest{
|
||||
Actor: actor,
|
||||
IDs: in.ids,
|
||||
Cascade: in.cascade,
|
||||
Force: in.force,
|
||||
DryRun: in.dryRun || !in.force,
|
||||
}
|
||||
|
||||
res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (domain.DeleteIssuesResult, string, error) {
|
||||
issueUC := uw.IssueUseCase()
|
||||
|
||||
preview, err := issueUC.PreviewDelete(ctx, in.ids)
|
||||
if err != nil {
|
||||
return domain.DeleteIssuesResult{}, "", fmt.Errorf("preview: %w", err)
|
||||
}
|
||||
if len(preview.NotFound) > 0 {
|
||||
return domain.DeleteIssuesResult{}, "", fmt.Errorf("issues not found: %s", strings.Join(preview.NotFound, ", "))
|
||||
}
|
||||
|
||||
res, err := issueUC.DeleteIssues(ctx, domain.DeleteIssuesParams{
|
||||
IDs: in.ids,
|
||||
Cascade: true,
|
||||
UpdateTextReferences: true,
|
||||
}, actor)
|
||||
if err != nil {
|
||||
return domain.DeleteIssuesResult{}, "", fmt.Errorf("delete: %w", err)
|
||||
}
|
||||
if res.DeletedCount == 0 {
|
||||
return domain.DeleteIssuesResult{}, "", fmt.Errorf("issues not found: %s", strings.Join(in.ids, ", "))
|
||||
}
|
||||
|
||||
return res, fmt.Sprintf("bd: delete %d issue(s)", res.DeletedCount), nil
|
||||
})
|
||||
result, err := deleter.Delete(ctx, request)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
|
||||
renderDeleteProxiedResult(in, res)
|
||||
if request.DryRun {
|
||||
// The role answered WHAT WOULD HAPPEN; this read answers WHICH ROWS,
|
||||
// which is presentation this route has always printed and which no
|
||||
// result carries. It runs only after the role accepted the request, so
|
||||
// a refusal costs it nothing.
|
||||
preview, err := runDeleteProxiedPreviewTx(ctx, in)
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
return outputDeleteProxiedPreview(in, deletePreviewResult{preview: preview, res: result})
|
||||
}
|
||||
|
||||
commandDidWrite.Store(true)
|
||||
renderDeleteProxiedResult(in, result)
|
||||
return nil
|
||||
}
|
||||
|
||||
type deletePreviewResult struct {
|
||||
preview domain.DeletePreview
|
||||
res domain.DeleteIssuesResult
|
||||
res issueops.DeleteResult
|
||||
}
|
||||
|
||||
func runDeleteProxiedPreviewTx(ctx context.Context, in *deleteInput) error {
|
||||
result, err := uow.RunTxRead(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (deletePreviewResult, error) {
|
||||
issueUC := uw.IssueUseCase()
|
||||
|
||||
preview, err := issueUC.PreviewDelete(ctx, in.ids)
|
||||
// runDeleteProxiedPreviewTx reads the titles and the neighborhood one preview
|
||||
// prints. It is a READ unit of work and decides nothing.
|
||||
func runDeleteProxiedPreviewTx(ctx context.Context, in *deleteInput) (domain.DeletePreview, error) {
|
||||
return uow.RunTxRead(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (domain.DeletePreview, error) {
|
||||
preview, err := uw.IssueUseCase().PreviewDelete(ctx, in.ids)
|
||||
if err != nil {
|
||||
return deletePreviewResult{}, fmt.Errorf("preview: %w", err)
|
||||
return domain.DeletePreview{}, fmt.Errorf("preview: %w", err)
|
||||
}
|
||||
if len(preview.NotFound) > 0 {
|
||||
return deletePreviewResult{}, fmt.Errorf("issues not found: %s", strings.Join(preview.NotFound, ", "))
|
||||
}
|
||||
|
||||
res, err := issueUC.DeleteIssues(ctx, domain.DeleteIssuesParams{
|
||||
IDs: in.ids,
|
||||
Cascade: true,
|
||||
DryRun: true,
|
||||
}, actor)
|
||||
if err != nil {
|
||||
return deletePreviewResult{}, fmt.Errorf("preview counts: %w", err)
|
||||
}
|
||||
|
||||
return deletePreviewResult{preview: preview, res: res}, nil
|
||||
return preview, nil
|
||||
})
|
||||
if err != nil {
|
||||
return HandleErrorRespectJSON("%v", err)
|
||||
}
|
||||
|
||||
return outputDeleteProxiedPreview(in, result)
|
||||
}
|
||||
|
||||
// outputDeleteProxiedPreview is the proxied-server preview output boundary.
|
||||
|
|
@ -136,10 +140,10 @@ func runDeleteProxiedPreviewTx(ctx context.Context, in *deleteInput) error {
|
|||
func outputDeleteProxiedPreview(in *deleteInput, result deletePreviewResult) error {
|
||||
if in.jsonOutput {
|
||||
return outputJSON(map[string]any{
|
||||
"would_delete": result.res.DeletedCount,
|
||||
"dependencies_removed": result.res.DependenciesCount,
|
||||
"labels_removed": result.res.LabelsCount,
|
||||
"events_removed": result.res.EventsCount,
|
||||
"would_delete": result.res.Deleted,
|
||||
"dependencies_removed": result.res.Dependencies,
|
||||
"labels_removed": result.res.Labels,
|
||||
"events_removed": result.res.Events,
|
||||
"ids": in.ids,
|
||||
"not_found": result.preview.NotFound,
|
||||
"connected": sortedKeys(result.preview.ConnectedIssues),
|
||||
|
|
@ -153,7 +157,7 @@ func outputDeleteProxiedPreview(in *deleteInput, result deletePreviewResult) err
|
|||
return nil
|
||||
}
|
||||
|
||||
func renderDeletePreview(in *deleteInput, preview domain.DeletePreview, res domain.DeleteIssuesResult) {
|
||||
func renderDeletePreview(in *deleteInput, preview domain.DeletePreview, res issueops.DeleteResult) {
|
||||
fmt.Printf("\n%s\n", ui.RenderFail("⚠️ DELETE PREVIEW"))
|
||||
fmt.Printf("\nIssues to delete (%d):\n", len(in.ids))
|
||||
for _, id := range in.ids {
|
||||
|
|
@ -163,12 +167,18 @@ func renderDeletePreview(in *deleteInput, preview domain.DeletePreview, res doma
|
|||
}
|
||||
fmt.Printf(" %s: %s\n", id, title)
|
||||
}
|
||||
fmt.Printf("\nCascade is always enabled — dependent issues will be removed.\n")
|
||||
if in.cascade {
|
||||
fmt.Printf("\nCascade mode enabled — dependent issues will be removed.\n")
|
||||
}
|
||||
fmt.Printf("\nWould remove:\n")
|
||||
fmt.Printf(" %d issue(s) total\n", res.DeletedCount)
|
||||
fmt.Printf(" %d dependency link(s)\n", res.DependenciesCount)
|
||||
fmt.Printf(" %d label(s)\n", res.LabelsCount)
|
||||
fmt.Printf(" %d event(s)\n", res.EventsCount)
|
||||
fmt.Printf(" %d issue(s) total\n", res.Deleted)
|
||||
fmt.Printf(" %d dependency link(s)\n", res.Dependencies)
|
||||
fmt.Printf(" %d label(s)\n", res.Labels)
|
||||
fmt.Printf(" %d event(s)\n", res.Events)
|
||||
if len(res.Orphaned) > 0 {
|
||||
fmt.Printf(" %s Would orphan %d issue(s): %s\n",
|
||||
ui.RenderWarn("⚠"), len(res.Orphaned), strings.Join(res.Orphaned, ", "))
|
||||
}
|
||||
|
||||
if len(preview.ConnectedIssues) > 0 {
|
||||
fmt.Printf("\nConnected issues (text references may be rewritten):\n")
|
||||
|
|
@ -187,27 +197,39 @@ func renderDeletePreview(in *deleteInput, preview domain.DeletePreview, res doma
|
|||
return
|
||||
}
|
||||
fmt.Printf("\n%s\n", ui.RenderWarn("This operation cannot be undone!"))
|
||||
if in.cascade {
|
||||
fmt.Printf("To proceed with cascade deletion, run: %s\n",
|
||||
ui.RenderWarn("bd delete "+strings.Join(in.ids, " ")+" --cascade --force"))
|
||||
return
|
||||
}
|
||||
fmt.Printf("To proceed, run: %s\n",
|
||||
ui.RenderWarn("bd delete "+strings.Join(in.ids, " ")+" --force"))
|
||||
}
|
||||
|
||||
func renderDeleteProxiedResult(in *deleteInput, res domain.DeleteIssuesResult) {
|
||||
func renderDeleteProxiedResult(in *deleteInput, res issueops.DeleteResult) {
|
||||
if in.jsonOutput {
|
||||
_ = outputJSON(map[string]any{
|
||||
"deleted": in.ids,
|
||||
"deleted_count": res.DeletedCount,
|
||||
"dependencies_removed": res.DependenciesCount,
|
||||
"labels_removed": res.LabelsCount,
|
||||
"events_removed": res.EventsCount,
|
||||
"deleted_count": res.Deleted,
|
||||
"dependencies_removed": res.Dependencies,
|
||||
"labels_removed": res.Labels,
|
||||
"events_removed": res.Events,
|
||||
"references_updated": res.ReferencesUpdated,
|
||||
// New on this route, and new because the behavior is: `--force`
|
||||
// used to cascade here, so there was never anything to orphan.
|
||||
"orphaned_issues": res.Orphaned,
|
||||
})
|
||||
return
|
||||
}
|
||||
fmt.Printf("%s Deleted %d issue(s)\n", ui.RenderPass("✓"), res.DeletedCount)
|
||||
fmt.Printf(" Removed %d dependency link(s)\n", res.DependenciesCount)
|
||||
fmt.Printf(" Removed %d label(s)\n", res.LabelsCount)
|
||||
fmt.Printf(" Removed %d event(s)\n", res.EventsCount)
|
||||
fmt.Printf("%s Deleted %d issue(s)\n", ui.RenderPass("✓"), res.Deleted)
|
||||
fmt.Printf(" Removed %d dependency link(s)\n", res.Dependencies)
|
||||
fmt.Printf(" Removed %d label(s)\n", res.Labels)
|
||||
fmt.Printf(" Removed %d event(s)\n", res.Events)
|
||||
fmt.Printf(" Updated text references in %d issue(s)\n", res.ReferencesUpdated)
|
||||
if len(res.Orphaned) > 0 {
|
||||
fmt.Printf(" %s Orphaned %d issue(s): %s\n",
|
||||
ui.RenderWarn("⚠"), len(res.Orphaned), strings.Join(res.Orphaned, ", "))
|
||||
}
|
||||
}
|
||||
|
||||
func sortedKeys[V any](m map[string]V) []string {
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import (
|
|||
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
func TestOutputDeleteProxiedPreviewIsPayloadBlind(t *testing.T) {
|
||||
|
|
@ -36,7 +37,7 @@ func TestOutputDeleteProxiedPreviewIsPayloadBlind(t *testing.T) {
|
|||
},
|
||||
},
|
||||
},
|
||||
res: domain.DeleteIssuesResult{DeletedCount: 1, DependenciesCount: 2},
|
||||
res: issueops.DeleteResult{Deleted: 1, Dependencies: 2},
|
||||
}
|
||||
markers := []string{titleMarker, descriptionMarker, notesMarker, payloadMarker}
|
||||
|
||||
|
|
@ -81,7 +82,7 @@ func TestOutputDeleteProxiedPreviewExactContracts(t *testing.T) {
|
|||
"bd-alpha": {ID: "bd-alpha", Title: "Alpha"},
|
||||
},
|
||||
},
|
||||
res: domain.DeleteIssuesResult{DeletedCount: 3, DependenciesCount: 4, LabelsCount: 2, EventsCount: 5},
|
||||
res: issueops.DeleteResult{Deleted: 3, Dependencies: 4, Labels: 2, Events: 5},
|
||||
}
|
||||
|
||||
t.Run("JSON includes the complete preview contract with sorted connections and takes precedence over quiet", func(t *testing.T) {
|
||||
|
|
@ -126,7 +127,7 @@ func TestOutputDeleteProxiedPreviewExactContracts(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestRenderDeleteProxiedResultExactContracts(t *testing.T) {
|
||||
res := domain.DeleteIssuesResult{DeletedCount: 3, DependenciesCount: 4, LabelsCount: 2, EventsCount: 5, ReferencesUpdated: 1}
|
||||
res := issueops.DeleteResult{Deleted: 3, Dependencies: 4, Labels: 2, Events: 5, ReferencesUpdated: 1, Orphaned: []string{"bd-orphan"}}
|
||||
|
||||
t.Run("JSON includes the complete final aggregate", func(t *testing.T) {
|
||||
in := &deleteInput{ids: []string{"bd-target", "bd-dependent"}, jsonOutput: true}
|
||||
|
|
@ -146,6 +147,9 @@ func TestRenderDeleteProxiedResultExactContracts(t *testing.T) {
|
|||
"labels_removed": float64(2),
|
||||
"events_removed": float64(5),
|
||||
"references_updated": float64(1),
|
||||
// New on this route with the cascade convergence: `--force` used
|
||||
// to take the dependents, so there was never anything to orphan.
|
||||
"orphaned_issues": []any{"bd-orphan"},
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("final JSON: got %#v, want %#v", got, want)
|
||||
|
|
@ -160,6 +164,7 @@ func TestRenderDeleteProxiedResultExactContracts(t *testing.T) {
|
|||
for _, required := range []string{
|
||||
"Deleted 3 issue(s)", "Removed 4 dependency link(s)", "Removed 2 label(s)",
|
||||
"Removed 5 event(s)", "Updated text references in 1 issue(s)",
|
||||
"Orphaned 1 issue(s): bd-orphan",
|
||||
} {
|
||||
if !strings.Contains(out, required) {
|
||||
t.Errorf("final prose missing %q:\n%s", required, out)
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import (
|
|||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
func TestDeletePreviewJSONIsPayloadBlind(t *testing.T) {
|
||||
|
|
@ -26,7 +27,7 @@ func TestDeletePreviewJSONIsPayloadBlind(t *testing.T) {
|
|||
Description: "sensitive payload must not appear",
|
||||
},
|
||||
}
|
||||
result := &types.DeleteIssuesResult{DeletedCount: 1, DependenciesCount: 2}
|
||||
result := &issueops.DeleteResult{Deleted: 1, Dependencies: 2}
|
||||
|
||||
out := captureStdout(t, func() error {
|
||||
return outputDeletionPreview([]string{"test-delete-1"}, issues, false, true, result, nil, true)
|
||||
|
|
|
|||
|
|
@ -163,7 +163,7 @@ func runServe() error {
|
|||
fmt.Fprintf(os.Stderr,
|
||||
"bd serve: WARNING: --allow-non-loopback binds %s beyond loopback. "+
|
||||
"This API has no authentication and no TLS: any peer that can reach it can read every issue, claim work as any actor, "+
|
||||
"and bulk-delete closed beads.\n",
|
||||
"bulk-delete closed beads, and delete any bead it can name.\n",
|
||||
serveAddr)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -193,7 +193,7 @@ type ContextResponse struct {
|
|||
// BeadsDir Absolute path of the served workspace's `.beads` directory. A host path, kept because it is the single-workspace server's only workspace-identity handshake; disclosing it to network peers is part of what an operator accepts when binding beyond loopback.
|
||||
BeadsDir string `json:"beads_dir"`
|
||||
|
||||
// Capabilities The operations this server actually implements, derived from its route table. v0's vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.get`, `issues.claim`, `issues.sweep`, `issues.batchCreate`, `stats.get`, `config.list`, `config.get`, `dependencies.cycles`, `dependencies.list`, `dependencies.blocking`; it grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation — never the version string.
|
||||
// Capabilities The operations this server actually implements, derived from its route table. v0's vocabulary is `ready.list`, `ready.count`, `issues.list`, `issues.query`, `issues.get`, `issues.claim`, `issues.sweep`, `issues.delete`, `issues.batchCreate`, `stats.get`, `config.list`, `config.get`, `dependencies.cycles`, `dependencies.list`, `dependencies.blocking`; it grows additively, and an operation never appears here unless it is fully implemented. This is how a client checks for an operation — never the version string.
|
||||
Capabilities []string `json:"capabilities"`
|
||||
|
||||
// Database Logical database name (not a host or a DSN).
|
||||
|
|
@ -233,6 +233,58 @@ type CyclesPage struct {
|
|||
Items []Cycle `json:"items"`
|
||||
}
|
||||
|
||||
// DeleteIssuesRequest Which beads to erase, and what to do about the beads that point at them. There is no predicate here — no status, no cutoff, no glob — and that absence is the reason this operation needs no require-a-filter gate: a caller cannot spell "everything" without typing every id.
|
||||
//
|
||||
// `additionalProperties: false`, so an unknown member is a `400` naming the member. On this operation a silently ignored member is the difference between orphaning a dependent and deleting it.
|
||||
type DeleteIssuesRequest struct {
|
||||
// Actor Caller-asserted attribution, under the same rules as `SweepRequest`'s `actor`: trimmed, refused when empty after trimming, over 256 BYTES, or carrying any control character. Optional — a deleted bead leaves no row to attribute the deletion on — but it does reach the SURVIVING beads whose text this operation rewrites, so a workspace that cares who rewrote a description sends one.
|
||||
Actor *string `json:"actor,omitempty"`
|
||||
|
||||
// Cascade Also delete the transitive closure of everything that depends on the named beads. With `cascade` there is nothing left outside the set to orphan, so it makes `force` moot rather than conflicting with it: a request carrying both behaves as `cascade` and `orphaned` comes back empty.
|
||||
Cascade *bool `json:"cascade,omitempty"`
|
||||
|
||||
// DryRun Report what the deletion WOULD do and change nothing. The counts and BOTH refusals are the ones the real request would produce, computed against the same snapshot, and nothing is recorded in history either.
|
||||
DryRun *bool `json:"dry_run,omitempty"`
|
||||
|
||||
// Force Delete the named beads and leave their dependents ORPHANED, reported in `orphaned`. Without it and without `cascade`, a named bead with a dependent the request did not name is refused.
|
||||
//
|
||||
// It defaults FALSE, which is the guarded mode, and the default is the protection: this surface has no authentication, so an omitted member must not silently choose the answer that changes another bead's graph.
|
||||
Force *bool `json:"force,omitempty"`
|
||||
|
||||
// Ids The beads to delete, exact ids, in either plane. DUPLICATES COLLAPSE. An empty array is a `400` rather than a no-op — a caller whose id list came out empty because its own construction broke would read "deleted 0" and conclude the workspace was already clean.
|
||||
//
|
||||
// The cap is on the REQUEST rather than on what a cascade expands to: the whole delete is one transaction, so the practical bound is the backend's write timeout and no number here can promise it.
|
||||
Ids []string `json:"ids"`
|
||||
}
|
||||
|
||||
// DeleteIssuesResult What one delete did. Every number describes the SAME snapshot, because the guard, the deletion and the reference rewrite ran in one transaction.
|
||||
//
|
||||
// It is NOT `x-go-type`-pinned, for the reason `SweepResult` is not: there is no canonical Go struct whose JSON encoding is this contract. `bd delete --json` publishes these numbers under its own per-shape keys (`deleted_count`, `dependencies_removed`, and a scalar `deleted` on the single-id form), which are a stdout presentation rather than a wire type, so pinning would weld this body to one of them.
|
||||
type DeleteIssuesResult struct {
|
||||
// Deleted How many beads were deleted, or under `dry_run` would be. Under `cascade` this counts the whole closure, so it is normally larger than `ids` and it — not the request length — is the number to show.
|
||||
Deleted int `json:"deleted"`
|
||||
|
||||
// Dependencies Dependency edge rows removed with them, in either direction. Reported because a delete's visible effect is much larger than its bead count.
|
||||
Dependencies int `json:"dependencies"`
|
||||
|
||||
// DryRun Echoes the request, so a result carries whether its numbers describe beads that are gone or beads that would go.
|
||||
DryRun bool `json:"dry_run"`
|
||||
|
||||
// Events Event rows removed with the deleted beads.
|
||||
Events int `json:"events"`
|
||||
|
||||
// Labels Label rows removed with the deleted beads.
|
||||
Labels int `json:"labels"`
|
||||
|
||||
// Orphaned The surviving beads that depended on something this request deleted, in ascending id order. Present exactly when the request carried `force` without `cascade`, which is the only mode in which orphaning is possible; absent otherwise.
|
||||
//
|
||||
// DIRECT dependents only. A bead two edges away lost no edge.
|
||||
Orphaned *[]string `json:"orphaned,omitempty"`
|
||||
|
||||
// ReferencesUpdated How many SURVIVING beads had their text rewritten — beads, not occurrences. Always 0 under `dry_run`, because a preview rewrites nothing.
|
||||
ReferencesUpdated int `json:"references_updated"`
|
||||
}
|
||||
|
||||
// Dependency A dependency edge between two issues.
|
||||
type Dependency = types.Dependency
|
||||
|
||||
|
|
@ -743,5 +795,8 @@ type ClaimIssueJSONRequestBody = ClaimRequest
|
|||
// BatchCreateIssuesJSONRequestBody defines body for BatchCreateIssues for application/json ContentType.
|
||||
type BatchCreateIssuesJSONRequestBody = BatchCreateRequest
|
||||
|
||||
// DeleteIssuesJSONRequestBody defines body for DeleteIssues for application/json ContentType.
|
||||
type DeleteIssuesJSONRequestBody = DeleteIssuesRequest
|
||||
|
||||
// SweepIssuesJSONRequestBody defines body for SweepIssues for application/json ContentType.
|
||||
type SweepIssuesJSONRequestBody = SweepRequest
|
||||
|
|
|
|||
|
|
@ -358,18 +358,13 @@ var (
|
|||
_ uow.IssueClaimerSource = timedProvider{}
|
||||
_ uow.WorkspaceConfigSource = timedProvider{}
|
||||
_ uow.StatsReporterSource = timedProvider{}
|
||||
_ uow.IssueReaderSource = timedProvider{}
|
||||
_ uow.IssueClaimerSource = timedProvider{}
|
||||
_ uow.CycleDetectorSource = timedProvider{}
|
||||
_ uow.IssueReaderSource = timedProvider{}
|
||||
_ uow.IssueClaimerSource = timedProvider{}
|
||||
_ uow.EdgeReaderSource = timedProvider{}
|
||||
_ uow.BlockingAnnotatorSource = timedProvider{}
|
||||
_ uow.IssueReaderSource = timedProvider{}
|
||||
_ uow.IssueClaimerSource = timedProvider{}
|
||||
_ uow.ReadyCounterSource = timedProvider{}
|
||||
_ uow.QuerierSource = timedProvider{}
|
||||
_ uow.SweeperSource = timedProvider{}
|
||||
_ uow.DeleterSource = timedProvider{}
|
||||
_ uow.BatchCreatorSource = timedProvider{}
|
||||
)
|
||||
|
||||
|
|
@ -466,6 +461,13 @@ func (p timedProvider) Sweeper() (issueops.Sweeper, error) {
|
|||
return uow.NewSweeper(p)
|
||||
}
|
||||
|
||||
// Deleter builds the deleter OVER THIS WRAPPER, for the same reason: it opens
|
||||
// the request's unit of work, so a deleter bound to the untimed provider would
|
||||
// leave the longest transaction on this surface out of uow_ms.
|
||||
func (p timedProvider) Deleter() (issueops.Deleter, error) {
|
||||
return uow.NewDeleter(p)
|
||||
}
|
||||
|
||||
// BatchCreator builds the batch creator OVER THIS WRAPPER, for the same reason
|
||||
// as the roles above and with more at stake than any of them: this is the one
|
||||
// role here that opens a WRITE unit of work per call, so a creator bound to the
|
||||
|
|
|
|||
241
internal/httpapi/delete.go
Normal file
241
internal/httpapi/delete.go
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/steveyegge/beads/internal/httpapi/apigen"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// The request body's member vocabulary. The schema is
|
||||
// additionalProperties: false, so anything else is refused BY NAME — the same
|
||||
// posture the sweep takes, and for the same reason sharpened: on this
|
||||
// operation an ignored member is the difference between orphaning a dependent
|
||||
// and deleting it.
|
||||
const (
|
||||
deleteIDsMember = "ids"
|
||||
deleteActorMember = "actor"
|
||||
deleteCascadeMember = "cascade"
|
||||
deleteForceMember = "force"
|
||||
deleteDryRunMember = "dry_run"
|
||||
)
|
||||
|
||||
// deleteMembers is the whole vocabulary, in one place, so the unknown-member
|
||||
// refusal and the decoding below cannot come to disagree about what this
|
||||
// operation accepts.
|
||||
var deleteMembers = []string{
|
||||
deleteIDsMember,
|
||||
deleteActorMember,
|
||||
deleteCascadeMember,
|
||||
deleteForceMember,
|
||||
deleteDryRunMember,
|
||||
}
|
||||
|
||||
// maxDeleteIDs bounds the `ids` array, matching the document's maxItems. It is
|
||||
// a bound on the REQUEST rather than on what a cascade expands to: the whole
|
||||
// delete is one transaction, so the practical ceiling is the backend's write
|
||||
// timeout and no number here can promise it.
|
||||
const maxDeleteIDs = 1000
|
||||
|
||||
// handleDelete answers POST /v0/beads/issues:delete — the second DESTRUCTIVE
|
||||
// operation on this surface.
|
||||
//
|
||||
// WHAT THIS HANDLER DOES NOT DO is the point of it, as for the sweep. It does
|
||||
// not resolve ids, does not expand a cascade, does not decide which rows are
|
||||
// dependents, and — the one that matters — does not implement the guard that
|
||||
// refuses an unforced delete over an outside dependent. All of that is
|
||||
// issueops.Deleter, the same library surface `bd delete` calls, so this
|
||||
// endpoint cannot orphan a workspace's graph by omission even if a future edit
|
||||
// here forgot the rule existed.
|
||||
//
|
||||
// Everything above the role here is argument validation: the media type, the
|
||||
// body shape, and the five members the document publishes.
|
||||
//
|
||||
// NO ACTOR IS INFERRED, for the reason the claim gives. It is OPTIONAL here as
|
||||
// it is on the sweep — a deleted bead leaves no row to attribute the deletion
|
||||
// on — and validated by the same rules when present, because it reaches the
|
||||
// same commit-message interpolation AND the surviving rows this operation
|
||||
// rewrites.
|
||||
func (s *Server) handleDelete(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.requireNoQuery(w, r) {
|
||||
return
|
||||
}
|
||||
if !s.requireJSONContent(w, r) {
|
||||
return
|
||||
}
|
||||
request, ok := s.deleteRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
deleter, err := s.deleter(r)
|
||||
if err != nil {
|
||||
s.failErr(w, r, err)
|
||||
return
|
||||
}
|
||||
result, err := deleter.Delete(r.Context(), request)
|
||||
if err != nil {
|
||||
s.failDeleteErr(w, r, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, deleteResponse(result))
|
||||
}
|
||||
|
||||
// deleteRequest decodes the body into the role's request, member by member, so
|
||||
// that every refusal can NAME the member it is about.
|
||||
func (s *Server) deleteRequest(w http.ResponseWriter, r *http.Request) (issueops.DeleteRequest, bool) {
|
||||
members, res := decodeJSONObjectBody(w, r)
|
||||
if res != nil {
|
||||
s.fail(w, r, *res)
|
||||
return issueops.DeleteRequest{}, false
|
||||
}
|
||||
|
||||
var unknown []string
|
||||
for name := range members {
|
||||
if !slices.Contains(deleteMembers, name) {
|
||||
unknown = append(unknown, name)
|
||||
}
|
||||
}
|
||||
if len(unknown) > 0 {
|
||||
// One offender, chosen deterministically so a client dispatching on
|
||||
// `param` never sees it depend on map order.
|
||||
offender := slices.Min(unknown)
|
||||
requestInfo(r.Context()).refuse(offender)
|
||||
s.fail(w, r, InvalidArgument(offender, ReasonUnknownParameter,
|
||||
"this operation's request body carries "+deleteMemberList()+" and nothing else"))
|
||||
return issueops.DeleteRequest{}, false
|
||||
}
|
||||
|
||||
// cascade, force and dry_run all default to their ZERO values here, unlike
|
||||
// the sweep's protect_referenced. That is not an inconsistency: false is
|
||||
// already the guarded answer for all three, so an omitted member cannot buy
|
||||
// weaker protection than the operator typing `bd delete` gets.
|
||||
var request issueops.DeleteRequest
|
||||
|
||||
raw, ok := members[deleteIDsMember]
|
||||
if !ok {
|
||||
s.fail(w, r, InvalidArgument(deleteIDsMember, ReasonInvalidValue,
|
||||
"`"+deleteIDsMember+"` is required"))
|
||||
return issueops.DeleteRequest{}, false
|
||||
}
|
||||
var ids *[]string
|
||||
if err := json.Unmarshal(raw, &ids); err != nil || ids == nil {
|
||||
s.fail(w, r, InvalidArgument(deleteIDsMember, ReasonInvalidValue,
|
||||
"`"+deleteIDsMember+"` must be an array of strings"))
|
||||
return issueops.DeleteRequest{}, false
|
||||
}
|
||||
if len(*ids) == 0 {
|
||||
// The ROLE refuses this too. It is refused here as well so the client
|
||||
// gets the member name, and because an empty array is the shape most
|
||||
// likely to arrive from a caller's own broken construction.
|
||||
s.fail(w, r, InvalidArgument(deleteIDsMember, ReasonInvalidValue,
|
||||
"`"+deleteIDsMember+"` must name at least one bead"))
|
||||
return issueops.DeleteRequest{}, false
|
||||
}
|
||||
if len(*ids) > maxDeleteIDs {
|
||||
s.fail(w, r, InvalidArgument(deleteIDsMember, ReasonInvalidValue,
|
||||
"`"+deleteIDsMember+"` carries more ids than this operation accepts in one request"))
|
||||
return issueops.DeleteRequest{}, false
|
||||
}
|
||||
request.IDs = *ids
|
||||
|
||||
if raw, ok := members[deleteActorMember]; ok {
|
||||
var value *string
|
||||
if err := json.Unmarshal(raw, &value); err != nil || value == nil {
|
||||
s.fail(w, r, InvalidArgument(deleteActorMember, ReasonInvalidValue,
|
||||
"`"+deleteActorMember+"` must be a string"))
|
||||
return issueops.DeleteRequest{}, false
|
||||
}
|
||||
// The claim's rules, unchanged, which is what makes the two operations
|
||||
// one vocabulary for a client.
|
||||
trimmed, res := validateActor(*value)
|
||||
if res != nil {
|
||||
s.fail(w, r, *res)
|
||||
return issueops.DeleteRequest{}, false
|
||||
}
|
||||
request.Actor = trimmed
|
||||
}
|
||||
|
||||
for _, flag := range []struct {
|
||||
member string
|
||||
dest *bool
|
||||
}{
|
||||
{deleteCascadeMember, &request.Cascade},
|
||||
{deleteForceMember, &request.Force},
|
||||
{deleteDryRunMember, &request.DryRun},
|
||||
} {
|
||||
raw, ok := members[flag.member]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
var value *bool
|
||||
if err := json.Unmarshal(raw, &value); err != nil || value == nil {
|
||||
s.fail(w, r, InvalidArgument(flag.member, ReasonInvalidValue,
|
||||
"`"+flag.member+"` must be a boolean"))
|
||||
return issueops.DeleteRequest{}, false
|
||||
}
|
||||
*flag.dest = *value
|
||||
}
|
||||
|
||||
return request, true
|
||||
}
|
||||
|
||||
func deleteMemberList() string {
|
||||
quoted := make([]string, len(deleteMembers))
|
||||
for i, name := range deleteMembers {
|
||||
quoted[i] = "`" + name + "`"
|
||||
}
|
||||
return strings.Join(quoted, ", ")
|
||||
}
|
||||
|
||||
// failDeleteErr answers a failed delete.
|
||||
//
|
||||
// It draws the same ErrValidation-is-a-400 line the sweep draws, and adds ONE
|
||||
// more: the role's dependents refusal. That one is a 400 rather than a 409
|
||||
// because the fix is to change the REQUEST — send `cascade` or `force` — and
|
||||
// the detail carries the role's own sentence, which names the blocked id and
|
||||
// says exactly that.
|
||||
//
|
||||
// THE ABSENT-ID REFUSAL NEEDS NO BRANCH AT ALL, and does not get one: the
|
||||
// role's *NotFoundError wraps issueops.ErrNotFound, which ClassifyError already
|
||||
// maps to a 404 carrying NotFound()'s FIXED detail. The role's own message
|
||||
// names every id that did not resolve and the wire deliberately does not repeat
|
||||
// it — NotFound's doc says why, and it is a posture about this whole surface
|
||||
// rather than about this operation. `bd delete` still names them, because it is
|
||||
// talking to the person who typed them.
|
||||
func (s *Server) failDeleteErr(w http.ResponseWriter, r *http.Request, err error) {
|
||||
if errors.Is(err, issueops.ErrValidation) || errors.Is(err, issueops.ErrDependentsOutsideRequest) {
|
||||
// No `param`: neither refusal is about one member of the request. The
|
||||
// dependents one is about the absence of a CHOICE between two of them,
|
||||
// and the document's `param` is documented absent on exactly that kind
|
||||
// of case.
|
||||
s.fail(w, r, InvalidArgument("", ReasonInvalidValue, err.Error()))
|
||||
return
|
||||
}
|
||||
s.failErr(w, r, err)
|
||||
}
|
||||
|
||||
// deleteResponse projects the role's result onto the wire type. It is a field
|
||||
// list rather than an alias for the reason sweepResponse is: DeleteResult is
|
||||
// deliberately not x-go-type-pinned, so the projection is where the two shapes
|
||||
// are held together and TestDeleteResponseCarriesEveryRoleField is what keeps a
|
||||
// new result field from being dropped here in silence.
|
||||
func deleteResponse(result issueops.DeleteResult) apigen.DeleteIssuesResult {
|
||||
body := apigen.DeleteIssuesResult{
|
||||
DryRun: result.DryRun,
|
||||
Deleted: result.Deleted,
|
||||
Dependencies: result.Dependencies,
|
||||
Labels: result.Labels,
|
||||
Events: result.Events,
|
||||
ReferencesUpdated: result.ReferencesUpdated,
|
||||
}
|
||||
if len(result.Orphaned) > 0 {
|
||||
ids := append([]string(nil), result.Orphaned...)
|
||||
body.Orphaned = &ids
|
||||
}
|
||||
return body
|
||||
}
|
||||
305
internal/httpapi/delete_test.go
Normal file
305
internal/httpapi/delete_test.go
Normal file
|
|
@ -0,0 +1,305 @@
|
|||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// The pins for POST /v0/beads/issues:delete. As with the sweep, what is
|
||||
// asserted here is the WIRE EDGE — that the handler decodes the document's five
|
||||
// members into the role's request faithfully, refuses what the document
|
||||
// refuses, and does not re-implement anything the role owns.
|
||||
|
||||
const deletePath = "/v0/beads/issues:delete"
|
||||
|
||||
func (ts *testServer) delete(t *testing.T, body string) *http.Response {
|
||||
t.Helper()
|
||||
return ts.claimRequest(t, deletePath, "application/json", body)
|
||||
}
|
||||
|
||||
// TestDeletePathReachesItsHandler is the sweep row's twin: a LITERAL segment
|
||||
// registered beside the claim's wildcard `/v0/beads/issues/{idop}`, where
|
||||
// ServeMux precedence is by specificity rather than by registration order. A
|
||||
// 404 or a claim-shaped refusal here would mean the delete is being parsed as a
|
||||
// claim of an issue named ":delete".
|
||||
func TestDeletePathReachesItsHandler(t *testing.T) {
|
||||
deleter := &roleDeleter{result: issueops.DeleteResult{Deleted: 1}}
|
||||
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
|
||||
|
||||
resp := ts.delete(t, `{"ids":["bd-1"],"force":true}`)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
if len(deleter.requests()) != 1 {
|
||||
t.Fatalf("the delete role was called %d times, want 1 — the path reached another handler",
|
||||
len(deleter.requests()))
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteForwardsEveryDocumentedMember is the operation's central pin: each
|
||||
// of the five body members reaches the role's request unchanged.
|
||||
//
|
||||
// It is asserted on the REQUEST the role received rather than on the response,
|
||||
// because a body carrying the right numbers says nothing about which beads went
|
||||
// — this is the operation where the handler dropping `cascade` deletes a
|
||||
// subtree the caller did not ask for.
|
||||
func TestDeleteForwardsEveryDocumentedMember(t *testing.T) {
|
||||
deleter := &roleDeleter{}
|
||||
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
|
||||
|
||||
resp := ts.delete(t, `{
|
||||
"ids": ["bd-1", "bd-2"],
|
||||
"actor": " alice ",
|
||||
"cascade": true,
|
||||
"force": true,
|
||||
"dry_run": true
|
||||
}`)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
|
||||
reqs := deleter.requests()
|
||||
if len(reqs) != 1 {
|
||||
t.Fatalf("%d deletes, want 1", len(reqs))
|
||||
}
|
||||
want := issueops.DeleteRequest{
|
||||
IDs: []string{"bd-1", "bd-2"},
|
||||
// TRIMMED, by the same rule and the same function the claim's actor
|
||||
// goes through: it reaches the same commit-message interpolation.
|
||||
Actor: "alice",
|
||||
Cascade: true,
|
||||
Force: true,
|
||||
DryRun: true,
|
||||
}
|
||||
if !reflect.DeepEqual(reqs[0], want) {
|
||||
t.Errorf("request = %+v, want %+v", reqs[0], want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteDefaultsTheOptionalMembers: a body carrying only `ids` reaches the
|
||||
// role as a GUARDED, non-cascading, real delete.
|
||||
//
|
||||
// All three flags default to their zero values, which is the one place this
|
||||
// operation's defaults differ in SPIRIT from the sweep's: there, false was the
|
||||
// unsafe answer for protect_referenced and the handler had to override it; here
|
||||
// false is the guarded answer for all three, so the zero value is the
|
||||
// protection and a handler that "helpfully" defaulted force on would be the
|
||||
// bug.
|
||||
func TestDeleteDefaultsTheOptionalMembers(t *testing.T) {
|
||||
deleter := &roleDeleter{}
|
||||
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
|
||||
|
||||
if resp := ts.delete(t, `{"ids":["bd-1"]}`); resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
reqs := deleter.requests()
|
||||
if len(reqs) != 1 {
|
||||
t.Fatalf("%d deletes, want 1", len(reqs))
|
||||
}
|
||||
want := issueops.DeleteRequest{IDs: []string{"bd-1"}}
|
||||
if !reflect.DeepEqual(reqs[0], want) {
|
||||
t.Errorf("request = %+v, want %+v", reqs[0], want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeletePublishesTheWholeResult drives every member of the response body,
|
||||
// which is the half deleteResponse owns: the schema is not x-go-type-pinned, so
|
||||
// a field added to the role's result and forgotten in the projection would be
|
||||
// silently absent from the wire.
|
||||
func TestDeletePublishesTheWholeResult(t *testing.T) {
|
||||
deleter := &roleDeleter{result: issueops.DeleteResult{
|
||||
DryRun: true,
|
||||
Deleted: 4,
|
||||
Dependencies: 7,
|
||||
Labels: 2,
|
||||
Events: 9,
|
||||
ReferencesUpdated: 3,
|
||||
Orphaned: []string{"bd-orphan-a", "bd-orphan-b"},
|
||||
}}
|
||||
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
|
||||
|
||||
resp := ts.delete(t, `{"ids":["bd-1"],"force":true,"dry_run":true}`)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
body := decodeBody(t, resp)
|
||||
want := map[string]any{
|
||||
"dry_run": true,
|
||||
"deleted": float64(4),
|
||||
"dependencies": float64(7),
|
||||
"labels": float64(2),
|
||||
"events": float64(9),
|
||||
"references_updated": float64(3),
|
||||
"orphaned": []any{"bd-orphan-a", "bd-orphan-b"},
|
||||
}
|
||||
if !reflect.DeepEqual(body, want) {
|
||||
t.Errorf("body = %#v, want %#v", body, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteOmitsAnEmptyOrphanList: `orphaned` is documented absent rather than
|
||||
// empty when nothing was orphaned, so a client can tell "this mode cannot
|
||||
// orphan" from "this mode could and did not".
|
||||
func TestDeleteOmitsAnEmptyOrphanList(t *testing.T) {
|
||||
deleter := &roleDeleter{result: issueops.DeleteResult{Deleted: 1}}
|
||||
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
|
||||
|
||||
body := decodeBody(t, ts.delete(t, `{"ids":["bd-1"],"cascade":true}`))
|
||||
if _, present := body["orphaned"]; present {
|
||||
t.Errorf("orphaned = %v, want it absent when nothing was orphaned", body["orphaned"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteRefusesTheDocumentedBodies(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
body string
|
||||
param string
|
||||
}{
|
||||
{"no ids", `{"force":true}`, "ids"},
|
||||
{"ids is not an array", `{"ids":"bd-1"}`, "ids"},
|
||||
{"ids is null", `{"ids":null}`, "ids"},
|
||||
{"ids is empty", `{"ids":[]}`, "ids"},
|
||||
{"ids carries a non-string", `{"ids":[3]}`, "ids"},
|
||||
{"unknown member", `{"ids":["bd-1"],"scope":"all"}`, "scope"},
|
||||
{"actor is not a string", `{"ids":["bd-1"],"actor":7}`, "actor"},
|
||||
{"actor is blank", `{"ids":["bd-1"],"actor":" "}`, "actor"},
|
||||
{"cascade is not a boolean", `{"ids":["bd-1"],"cascade":"yes"}`, "cascade"},
|
||||
{"force is not a boolean", `{"ids":["bd-1"],"force":1}`, "force"},
|
||||
{"dry_run is not a boolean", `{"ids":["bd-1"],"dry_run":"yes"}`, "dry_run"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
deleter := &roleDeleter{}
|
||||
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
|
||||
|
||||
resp := ts.delete(t, test.body)
|
||||
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 %s", body["code"], CodeInvalidArgument)
|
||||
}
|
||||
if body["param"] != test.param {
|
||||
t.Errorf("param = %v, want %q", body["param"], test.param)
|
||||
}
|
||||
// A refused body must never reach the role: this is destructive,
|
||||
// and "refused after acting" is the one failure shape worth ruling
|
||||
// out at every edge.
|
||||
if got := len(deleter.requests()); got != 0 {
|
||||
t.Errorf("the role was called %d times for a refused body, want 0", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeletePublishesTheRolesGuardAsA400 is the reason failDeleteErr exists.
|
||||
//
|
||||
// The dependents guard is refused BELOW the wire, by issueops.Deleter — that is
|
||||
// what makes this endpoint incapable of orphaning a graph by omission. The
|
||||
// refusal reaching the client as a 500 would tell it the server was broken when
|
||||
// the request was, and would hide the one sentence that says what to send
|
||||
// instead.
|
||||
func TestDeletePublishesTheRolesGuardAsA400(t *testing.T) {
|
||||
// The typed error, not a lookalike: the handler keys on the sentinel it
|
||||
// wraps.
|
||||
deleter := &roleDeleter{err: &issueops.DependentsOutsideRequestError{
|
||||
IssueID: "bd-blocker",
|
||||
Dependents: []string{"bd-dependent"},
|
||||
}}
|
||||
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
|
||||
|
||||
resp := ts.delete(t, `{"ids":["bd-blocker"]}`)
|
||||
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 %s", body["code"], CodeInvalidArgument)
|
||||
}
|
||||
if detail, _ := body["detail"].(string); !strings.Contains(detail, "bd-blocker") {
|
||||
t.Errorf("detail = %q, want the role's own sentence naming the blocked bead", detail)
|
||||
}
|
||||
// No `param`: the refusal is about the absence of a CHOICE between two
|
||||
// members, and the document declares `param` absent on that case.
|
||||
if _, present := body["param"]; present {
|
||||
t.Errorf("param = %v, want it absent for a whole-request refusal", body["param"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeletePublishesAnAbsentIDAsA404 pins the other refusal, and pins that its
|
||||
// detail does NOT name the ids.
|
||||
//
|
||||
// That is deliberate and is this surface's posture rather than this operation's
|
||||
// preference: NotFound's fixed sentence is what keeps a handler that decided a
|
||||
// miss without reading storage indistinguishable from one that read and missed.
|
||||
// `bd delete` still names them, because it is answering the person who typed
|
||||
// them.
|
||||
func TestDeletePublishesAnAbsentIDAsA404(t *testing.T) {
|
||||
deleter := &roleDeleter{err: &issueops.NotFoundError{IDs: []string{"bd-nosuch"}}}
|
||||
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
|
||||
|
||||
resp := ts.delete(t, `{"ids":["bd-nosuch"],"force":true}`)
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want 404: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
body := decodeBody(t, resp)
|
||||
if body["code"] != string(CodeNotFound) {
|
||||
t.Errorf("code = %v, want %s", body["code"], CodeNotFound)
|
||||
}
|
||||
if detail, _ := body["detail"].(string); strings.Contains(detail, "bd-nosuch") {
|
||||
t.Errorf("detail = %q, want this surface's fixed not-found sentence without the id", detail)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteRefusesAForeignMediaType: the CSRF control the claim documents, for
|
||||
// the reason the sweep gives — accepting text/plain would let an attacker's
|
||||
// page drive a delete from any browser on the host, and this one does not even
|
||||
// need the beads to be closed.
|
||||
func TestDeleteRefusesAForeignMediaType(t *testing.T) {
|
||||
deleter := &roleDeleter{}
|
||||
ts := newTestServer(t, rolesConfig(Config{Deleter: deleter}))
|
||||
|
||||
resp := ts.claimRequest(t, deletePath, "text/plain", `{"ids":["bd-1"]}`)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
if body := decodeBody(t, resp); body["param"] != "Content-Type" {
|
||||
t.Errorf("param = %v, want Content-Type", body["param"])
|
||||
}
|
||||
if got := len(deleter.requests()); got != 0 {
|
||||
t.Errorf("the role was called %d times for a refused media type, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeletePublishesNoQueryParameters: this operation's whole vocabulary is
|
||||
// its body, so a query key is version skew rather than a bad value.
|
||||
func TestDeletePublishesNoQueryParameters(t *testing.T) {
|
||||
ts := newTestServer(t, rolesConfig(Config{Deleter: &roleDeleter{}}))
|
||||
|
||||
resp := ts.claimRequest(t, deletePath+"?force=true", "application/json", `{"ids":["bd-1"]}`)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
|
||||
}
|
||||
body := decodeBody(t, resp)
|
||||
if body["param"] != "force" || body["reason"] != string(ReasonUnknownParameter) {
|
||||
t.Errorf("body = %v, want unknown_parameter on param force", body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteResponseCarriesEveryRoleField is the guard the missing x-go-type
|
||||
// pin costs. deleteResponse is a hand-written projection, so a field added to
|
||||
// issueops.DeleteResult and forgotten there would vanish from the wire with
|
||||
// nothing to notice; this counts the fields and fails when the two drift.
|
||||
func TestDeleteResponseCarriesEveryRoleField(t *testing.T) {
|
||||
role := reflect.TypeOf(issueops.DeleteResult{}).NumField()
|
||||
wire := reflect.TypeOf(deleteResponse(issueops.DeleteResult{})).NumField()
|
||||
if role != wire {
|
||||
t.Fatalf("issueops.DeleteResult has %d fields and the wire type has %d: "+
|
||||
"a field was added to one and not projected onto the other (see deleteResponse)", role, wire)
|
||||
}
|
||||
}
|
||||
|
|
@ -170,6 +170,11 @@ const (
|
|||
// OpSweepIssues is the one DESTRUCTIVE operation on this surface: bulk
|
||||
// clearance of closed beads from one tier, behind issueops.Sweeper.
|
||||
OpSweepIssues = "sweepIssues"
|
||||
// OpDeleteIssues is the other DESTRUCTIVE operation: erasure of beads the
|
||||
// request NAMES, behind issueops.Deleter. It is the one operation on this
|
||||
// surface whose refusals include a question about the GRAPH — a named bead
|
||||
// with a dependent the request did not name — as well as about the request.
|
||||
OpDeleteIssues = "deleteIssues"
|
||||
// OpBatchCreateIssues creates many issues as one transaction, or none.
|
||||
OpBatchCreateIssues = "batchCreateIssues"
|
||||
)
|
||||
|
|
@ -242,6 +247,10 @@ var operationCodes = map[string][]Code{
|
|||
// this operation names no id — and no 409: a sweep has nothing to conflict
|
||||
// with, since a bead another sweep already took is simply not in the set.
|
||||
OpSweepIssues: {CodeInvalidArgument, CodeBusy, CodeDBUnavailable, CodeInternal},
|
||||
// CodeNotFound is the one this operation has and the sweep does not: a
|
||||
// sweep describes a set that can legitimately be empty, while a delete
|
||||
// names beads and an id that resolves to nothing is a caller mistake.
|
||||
OpDeleteIssues: {CodeInvalidArgument, CodeNotFound, CodeBusy, CodeDBUnavailable, CodeInternal},
|
||||
OpClaimIssue: {
|
||||
CodeInvalidArgument, CodeNotFound, CodeAlreadyClaimed, CodeNotClaimable,
|
||||
CodeBusy, CodeDBUnavailable, CodeInternal,
|
||||
|
|
|
|||
|
|
@ -384,6 +384,9 @@ func rolesConfig(cfg Config) Config {
|
|||
if cfg.Sweeper == nil {
|
||||
cfg.Sweeper = &roleSweeper{}
|
||||
}
|
||||
if cfg.Deleter == nil {
|
||||
cfg.Deleter = &roleDeleter{}
|
||||
}
|
||||
if cfg.BatchCreator == nil {
|
||||
cfg.BatchCreator = &roleBatchCreator{}
|
||||
}
|
||||
|
|
@ -451,6 +454,34 @@ func (s *roleSweeper) requests() []issueops.SweepRequest {
|
|||
return append([]issueops.SweepRequest(nil), s.calls...)
|
||||
}
|
||||
|
||||
// roleDeleter is the store-shaped source's named-row erasure role, the same
|
||||
// shape as roleSweeper and for the same reason: the alternative to a complete
|
||||
// source is a server that binds and then nil-dereferences on a request that
|
||||
// deletes beads.
|
||||
type roleDeleter struct {
|
||||
result issueops.DeleteResult
|
||||
err error
|
||||
|
||||
mu sync.Mutex
|
||||
calls []issueops.DeleteRequest
|
||||
}
|
||||
|
||||
func (d *roleDeleter) Delete(_ context.Context, req issueops.DeleteRequest) (issueops.DeleteResult, error) {
|
||||
d.mu.Lock()
|
||||
d.calls = append(d.calls, req)
|
||||
d.mu.Unlock()
|
||||
if d.err != nil {
|
||||
return issueops.DeleteResult{}, d.err
|
||||
}
|
||||
return d.result, nil
|
||||
}
|
||||
|
||||
func (d *roleDeleter) requests() []issueops.DeleteRequest {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
return append([]issueops.DeleteRequest(nil), d.calls...)
|
||||
}
|
||||
|
||||
// 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 {
|
||||
|
|
|
|||
|
|
@ -232,6 +232,18 @@ var routeTable = []route{
|
|||
implemented: true,
|
||||
handler: (*Server).handleSweep,
|
||||
},
|
||||
{
|
||||
op: OpDeleteIssues,
|
||||
method: http.MethodPost,
|
||||
// A literal collection-level custom method, registered and preferred
|
||||
// over the claim's wildcard for exactly the reason the sweep row above
|
||||
// spells out; TestDeletePathReachesItsHandler drives the documented
|
||||
// path.
|
||||
pattern: "/v0/beads/issues:delete",
|
||||
capability: "issues.delete",
|
||||
implemented: true,
|
||||
handler: (*Server).handleDelete,
|
||||
},
|
||||
}
|
||||
|
||||
// specPathOf is the document path for a route, defaulting to the router
|
||||
|
|
|
|||
|
|
@ -213,7 +213,12 @@ type Config struct {
|
|||
// be a Config that quietly decides whether this build erases beads, which
|
||||
// is a decision that belongs to the operator who chose to run bd serve at
|
||||
// all — not to whether a caller remembered a field.
|
||||
Sweeper issueops.Sweeper
|
||||
Sweeper issueops.Sweeper
|
||||
// Deleter is the OTHER destructive one, required on the same terms and for
|
||||
// the same reason: whether this build can erase named beads is the
|
||||
// operator's decision, not a consequence of whether a caller remembered a
|
||||
// field.
|
||||
Deleter issueops.Deleter
|
||||
BatchCreator issueops.BatchCreator
|
||||
// Workspace is the startup snapshot GET /v0/beads/context answers from.
|
||||
// Only the allowlisted fields are ever serialized — see contextResponse,
|
||||
|
|
@ -260,6 +265,7 @@ type Server struct {
|
|||
issueReadyCounter issueops.ReadyCounter
|
||||
issueQuerier issueops.Querier
|
||||
issueSweeper issueops.Sweeper
|
||||
issueDeleter issueops.Deleter
|
||||
issueBatchCreator issueops.BatchCreator
|
||||
|
||||
listener net.Listener
|
||||
|
|
@ -367,6 +373,7 @@ func Listen(cfg Config) (*Server, error) {
|
|||
issueReadyCounter: cfg.ReadyCounter,
|
||||
issueQuerier: cfg.Querier,
|
||||
issueSweeper: cfg.Sweeper,
|
||||
issueDeleter: cfg.Deleter,
|
||||
issueBatchCreator: cfg.BatchCreator,
|
||||
|
||||
sem: make(chan struct{}, maxInflight),
|
||||
|
|
@ -471,12 +478,12 @@ func Listen(cfg Config) (*Server, error) {
|
|||
// as this check is concerned, exactly as it was when the check was a hand-
|
||||
// written boolean per role.
|
||||
func sourceRoles(cfg Config) []any {
|
||||
return []any{cfg.Reader, cfg.Claimer, cfg.Settings, cfg.Stats, cfg.CycleDetector, cfg.EdgeReader, cfg.BlockingAnnotator, cfg.ReadyCounter, cfg.Querier, cfg.Sweeper, cfg.BatchCreator}
|
||||
return []any{cfg.Reader, cfg.Claimer, cfg.Settings, cfg.Stats, cfg.CycleDetector, cfg.EdgeReader, cfg.BlockingAnnotator, cfg.ReadyCounter, cfg.Querier, cfg.Sweeper, cfg.Deleter, cfg.BatchCreator}
|
||||
}
|
||||
|
||||
// roleSourceNames spells sourceRoles for the refusal message, in the same
|
||||
// order, so a caller reading the error learns the whole set it must pass.
|
||||
const roleSourceNames = "Reader, Claimer, Settings, Stats, CycleDetector, EdgeReader, BlockingAnnotator, ReadyCounter, Querier, Sweeper and BatchCreator"
|
||||
const roleSourceNames = "Reader, Claimer, Settings, Stats, CycleDetector, EdgeReader, BlockingAnnotator, ReadyCounter, Querier, Sweeper, Deleter and BatchCreator"
|
||||
|
||||
func anyRoleSet(cfg Config) bool {
|
||||
return slices.ContainsFunc(sourceRoles(cfg), func(r any) bool { return r != nil })
|
||||
|
|
@ -771,6 +778,25 @@ func (s *Server) sweeper(r *http.Request) (issueops.Sweeper, error) {
|
|||
return src.Sweeper()
|
||||
}
|
||||
|
||||
// deleter returns the named-row erasure surface for one request.
|
||||
//
|
||||
// The same two sources as every role above, for the same reasons, and held by
|
||||
// INTERFACE so uow.DeleterSource is load-bearing rather than decorative. It
|
||||
// goes out unwrapped for the reason the sweeper does: DeleteResult is a VALUE,
|
||||
// so there is no pointer for a caller-supplied role to hand back nil in.
|
||||
//
|
||||
// The role this returns is the only thing standing between a POST body and an
|
||||
// orphaned dependency graph — the guard, the id resolution and the reference
|
||||
// rewrite are all inside it — which is why the Config field it comes from is
|
||||
// required rather than optional.
|
||||
func (s *Server) deleter(r *http.Request) (issueops.Deleter, error) {
|
||||
if s.provider == nil {
|
||||
return s.issueDeleter, nil
|
||||
}
|
||||
var src uow.DeleterSource = timedProvider{inner: s.provider, rec: requestInfo(r.Context())}
|
||||
return src.Deleter()
|
||||
}
|
||||
|
||||
// batchCreator returns the batch-create surface for one request, the same two
|
||||
// ways every other role is reached: the configured role on the roles source,
|
||||
// one built per request on the provider source so the unit of work the batch
|
||||
|
|
|
|||
|
|
@ -579,8 +579,9 @@ func TestCapabilitiesAdvertiseEveryImplementedOperation(t *testing.T) {
|
|||
want := []string{
|
||||
"config.get", "config.list", "dependencies.blocking", "dependencies.cycles",
|
||||
"dependencies.list",
|
||||
"issues.batchCreate", "issues.claim", "issues.get", "issues.list",
|
||||
"issues.query", "issues.sweep", "ready.count", "ready.list", "stats.get",
|
||||
"issues.batchCreate", "issues.claim", "issues.delete", "issues.get",
|
||||
"issues.list", "issues.query", "issues.sweep", "ready.count",
|
||||
"ready.list", "stats.get",
|
||||
}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Errorf("capabilities = %v, want %v", got, want)
|
||||
|
|
|
|||
|
|
@ -57,7 +57,8 @@ info:
|
|||
Operations with no parameters at all (`GET /healthz`,
|
||||
`GET /v0/beads/context`, `GET /v0/beads/dependencies/cycles`,
|
||||
`GET /v0/beads/issues/{id}`, `POST /v0/beads/issues/{id}:claim`,
|
||||
`POST /v0/beads/issues:sweep`, `GET /v0/beads/config`,
|
||||
`POST /v0/beads/issues:sweep`, `POST /v0/beads/issues:delete`,
|
||||
`GET /v0/beads/config`,
|
||||
`GET /v0/beads/config/{key}`) reject every query key the same way.
|
||||
|
||||
|
||||
|
|
@ -1230,6 +1231,117 @@ paths:
|
|||
'503':
|
||||
$ref: '#/components/responses/Unavailable'
|
||||
|
||||
/v0/beads/issues:delete:
|
||||
post:
|
||||
operationId: deleteIssues
|
||||
summary: Delete named beads
|
||||
description: >-
|
||||
Erases the beads this request NAMES, and — under `cascade` — everything
|
||||
that depends on them. It is the operation behind `bd delete`, the
|
||||
second DESTRUCTIVE operation on this surface, and nothing it deletes
|
||||
comes back.
|
||||
|
||||
|
||||
It is a different operation from `POST /v0/beads/issues:sweep`, not a
|
||||
narrower spelling of it. A sweep DESCRIBES a set and lets the server
|
||||
resolve it; this one is handed ids. That difference is what decides
|
||||
where each one's safety lives: a description can be accidentally too
|
||||
wide, so the sweep carries a require-a-filter refusal, while a list of
|
||||
ids cannot be, so this one's guard is about the GRAPH instead.
|
||||
|
||||
|
||||
A collection-level custom method rather than `DELETE
|
||||
/v0/beads/issues/{id}`: this acts on a SET, its behaviour turns on
|
||||
three flags, and a `DELETE` carrying those in a query string is the
|
||||
shape where a dropped parameter changes what is erased. Sending a body
|
||||
makes every one of them a member the server refuses by name if it does
|
||||
not know it.
|
||||
|
||||
|
||||
## The three modes
|
||||
|
||||
|
||||
With neither `cascade` nor `force`, a named bead that some bead OUTSIDE
|
||||
the request depends on is REFUSED with `400` / `invalid_argument`, and
|
||||
nothing is deleted. `force` deletes the named beads and leaves those
|
||||
dependents ORPHANED — they keep their rows, lose their edges, and come
|
||||
back in `orphaned`. `cascade` deletes the transitive closure instead,
|
||||
so nothing is left outside it to orphan; a request carrying both
|
||||
behaves as `cascade`.
|
||||
|
||||
|
||||
The refusal is the LIBRARY's, not this handler's — the same surface
|
||||
`bd delete` calls — which is what makes this endpoint incapable of
|
||||
orphaning a workspace's graph by omission.
|
||||
|
||||
|
||||
## Every id must resolve
|
||||
|
||||
|
||||
An id naming no stored bead is a `404` and NOTHING is deleted, not even
|
||||
the ids beside it that did resolve. There is no prefix matching here:
|
||||
ids are exact, because resolving an ambiguous prefix to a bead and then
|
||||
deleting it is the one place that convenience is not one.
|
||||
|
||||
|
||||
## One transaction
|
||||
|
||||
|
||||
The guard, the deletion and the rewrite of surviving beads' text
|
||||
references all share one transaction, so the set the response describes
|
||||
IS the set that was deleted and no bead is left citing an id that no
|
||||
longer exists. The cost is that a delete is all-or-nothing: one whose
|
||||
neighbourhood is large enough to exceed the backend's write timeout
|
||||
fails whole. Split the request rather than expecting progress.
|
||||
|
||||
|
||||
`dry_run: true` answers the same question and changes nothing —
|
||||
including history, and including the two refusals, which a preview
|
||||
reports exactly where the real request would. Ask it first.
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/DeleteIssuesRequest'
|
||||
responses:
|
||||
'200':
|
||||
description: >-
|
||||
The beads were deleted (or, under `dry_run`, costed).
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/DeleteIssuesResult'
|
||||
'400':
|
||||
description: >-
|
||||
Invalid request: an unparseable or oversized body, an unknown body
|
||||
member, an empty or over-long `ids`, a blank id, an `actor` that is
|
||||
empty after trimming or carries control characters — or a named
|
||||
bead with a dependent the request did not name and neither
|
||||
`cascade` nor `force` to say what to do about it, which the library
|
||||
surface refuses as a safety invariant.
|
||||
x-bd-codes: [invalid_argument]
|
||||
content:
|
||||
application/problem+json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Problem'
|
||||
'404':
|
||||
description: >-
|
||||
At least one id named no stored bead, and nothing was deleted.
|
||||
`detail` is this surface's fixed not-found sentence and does NOT
|
||||
name which ids missed: a client able to tell a well-formed miss
|
||||
from a malformed id would be probing the id space. `bd delete`
|
||||
names them, because it is answering the person who typed them.
|
||||
x-bd-codes: [not_found]
|
||||
content:
|
||||
application/problem+json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/Problem'
|
||||
'500':
|
||||
$ref: '#/components/responses/InternalError'
|
||||
'503':
|
||||
$ref: '#/components/responses/Unavailable'
|
||||
|
||||
/v0/beads/issues:batchCreate:
|
||||
post:
|
||||
operationId: batchCreateIssues
|
||||
|
|
@ -2461,7 +2573,7 @@ components:
|
|||
The operations this server actually implements, derived from its
|
||||
route table. v0's vocabulary is `ready.list`, `ready.count`,
|
||||
`issues.list`, `issues.query`, `issues.get`, `issues.claim`,
|
||||
`issues.sweep`, `issues.batchCreate`,
|
||||
`issues.sweep`, `issues.delete`, `issues.batchCreate`,
|
||||
`stats.get`, `config.list`, `config.get`, `dependencies.cycles`,
|
||||
`dependencies.list`, `dependencies.blocking`; it grows additively,
|
||||
and an operation never
|
||||
|
|
@ -2497,6 +2609,140 @@ components:
|
|||
pinning would weld this body to a CLI presentation type instead of
|
||||
preventing a drift.
|
||||
|
||||
DeleteIssuesRequest:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
required: [ids]
|
||||
description: >-
|
||||
Which beads to erase, and what to do about the beads that point at
|
||||
them. There is no predicate here — no status, no cutoff, no glob — and
|
||||
that absence is the reason this operation needs no require-a-filter
|
||||
gate: a caller cannot spell "everything" without typing every id.
|
||||
|
||||
|
||||
`additionalProperties: false`, so an unknown member is a `400` naming
|
||||
the member. On this operation a silently ignored member is the
|
||||
difference between orphaning a dependent and deleting it.
|
||||
properties:
|
||||
ids:
|
||||
type: array
|
||||
minItems: 1
|
||||
maxItems: 1000
|
||||
description: >-
|
||||
The beads to delete, exact ids, in either plane. DUPLICATES
|
||||
COLLAPSE. An empty array is a `400` rather than a no-op — a caller
|
||||
whose id list came out empty because its own construction broke
|
||||
would read "deleted 0" and conclude the workspace was already
|
||||
clean.
|
||||
|
||||
|
||||
The cap is on the REQUEST rather than on what a cascade expands to:
|
||||
the whole delete is one transaction, so the practical bound is the
|
||||
backend's write timeout and no number here can promise it.
|
||||
items:
|
||||
type: string
|
||||
actor:
|
||||
type: string
|
||||
minLength: 1
|
||||
maxLength: 256
|
||||
pattern: '^[^\u0000-\u001F\u007F]+$'
|
||||
description: >-
|
||||
Caller-asserted attribution, under the same rules as
|
||||
`SweepRequest`'s `actor`: trimmed, refused when empty after
|
||||
trimming, over 256 BYTES, or carrying any control character.
|
||||
Optional — a deleted bead leaves no row to attribute the deletion
|
||||
on — but it does reach the SURVIVING beads whose text this
|
||||
operation rewrites, so a workspace that cares who rewrote a
|
||||
description sends one.
|
||||
cascade:
|
||||
type: boolean
|
||||
default: false
|
||||
description: >-
|
||||
Also delete the transitive closure of everything that depends on
|
||||
the named beads. With `cascade` there is nothing left outside the
|
||||
set to orphan, so it makes `force` moot rather than conflicting
|
||||
with it: a request carrying both behaves as `cascade` and
|
||||
`orphaned` comes back empty.
|
||||
force:
|
||||
type: boolean
|
||||
default: false
|
||||
description: >-
|
||||
Delete the named beads and leave their dependents ORPHANED,
|
||||
reported in `orphaned`. Without it and without `cascade`, a named
|
||||
bead with a dependent the request did not name is refused.
|
||||
|
||||
|
||||
It defaults FALSE, which is the guarded mode, and the default is
|
||||
the protection: this surface has no authentication, so an omitted
|
||||
member must not silently choose the answer that changes another
|
||||
bead's graph.
|
||||
dry_run:
|
||||
type: boolean
|
||||
default: false
|
||||
description: >-
|
||||
Report what the deletion WOULD do and change nothing. The counts
|
||||
and BOTH refusals are the ones the real request would produce,
|
||||
computed against the same snapshot, and nothing is recorded in
|
||||
history either.
|
||||
|
||||
DeleteIssuesResult:
|
||||
type: object
|
||||
required: [dry_run, deleted, dependencies, labels, events, references_updated]
|
||||
description: >-
|
||||
What one delete did. Every number describes the SAME snapshot, because
|
||||
the guard, the deletion and the reference rewrite ran in one
|
||||
transaction.
|
||||
|
||||
|
||||
It is NOT `x-go-type`-pinned, for the reason `SweepResult` is not:
|
||||
there is no canonical Go struct whose JSON encoding is this contract.
|
||||
`bd delete --json` publishes these numbers under its own per-shape keys
|
||||
(`deleted_count`, `dependencies_removed`, and a scalar `deleted` on the
|
||||
single-id form), which are a stdout presentation rather than a wire
|
||||
type, so pinning would weld this body to one of them.
|
||||
properties:
|
||||
dry_run:
|
||||
type: boolean
|
||||
description: >-
|
||||
Echoes the request, so a result carries whether its numbers
|
||||
describe beads that are gone or beads that would go.
|
||||
deleted:
|
||||
type: integer
|
||||
description: >-
|
||||
How many beads were deleted, or under `dry_run` would be. Under
|
||||
`cascade` this counts the whole closure, so it is normally larger
|
||||
than `ids` and it — not the request length — is the number to show.
|
||||
dependencies:
|
||||
type: integer
|
||||
description: >-
|
||||
Dependency edge rows removed with them, in either direction.
|
||||
Reported because a delete's visible effect is much larger than its
|
||||
bead count.
|
||||
labels:
|
||||
type: integer
|
||||
description: Label rows removed with the deleted beads.
|
||||
events:
|
||||
type: integer
|
||||
description: Event rows removed with the deleted beads.
|
||||
references_updated:
|
||||
type: integer
|
||||
description: >-
|
||||
How many SURVIVING beads had their text rewritten — beads, not
|
||||
occurrences. Always 0 under `dry_run`, because a preview rewrites
|
||||
nothing.
|
||||
orphaned:
|
||||
type: array
|
||||
description: >-
|
||||
The surviving beads that depended on something this request
|
||||
deleted, in ascending id order. Present exactly when the request
|
||||
carried `force` without `cascade`, which is the only mode in which
|
||||
orphaning is possible; absent otherwise.
|
||||
|
||||
|
||||
DIRECT dependents only. A bead two edges away lost no edge.
|
||||
items:
|
||||
type: string
|
||||
|
||||
SweepRequest:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
|
|
|
|||
|
|
@ -690,6 +690,10 @@ func (s *configStore) Querier() (issueops.Querier, error) {
|
|||
return nil, &storage.ErrUnsupported{Op: "Querier", Backend: "jira-config-stub"}
|
||||
}
|
||||
|
||||
func (s *configStore) Deleter() (issueops.Deleter, error) {
|
||||
return nil, &storage.ErrUnsupported{Op: "Deleter", Backend: "jira-config-stub"}
|
||||
}
|
||||
|
||||
func (s *configStore) Sweeper() (issueops.Sweeper, error) {
|
||||
return nil, &storage.ErrUnsupported{Op: "Sweeper", Backend: "jira-config-stub"}
|
||||
}
|
||||
|
|
|
|||
98
internal/storage/dolt/deleter.go
Normal file
98
internal/storage/dolt/deleter.go
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
package dolt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
storeops "github.com/steveyegge/beads/internal/storage/issueops"
|
||||
"github.com/steveyegge/beads/internal/storage/schema"
|
||||
"github.com/steveyegge/beads/internal/workapi"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// Deleter returns the named-row erasure surface for this store.
|
||||
func (s *DoltStore) Deleter() (issueops.Deleter, error) {
|
||||
if s == nil {
|
||||
return nil, &storage.ErrUnsupported{Op: "Deleter", Backend: "nil"}
|
||||
}
|
||||
return &deleter{store: s}, nil
|
||||
}
|
||||
|
||||
// deleter erases named rows inside ONE transaction.
|
||||
//
|
||||
// There is no shared constructor package for this role, for the reason sweeper
|
||||
// gives: the work is an existence probe, a guard, a delete and a text rewrite
|
||||
// that must all see one snapshot, and a transaction is not reachable through
|
||||
// storage.DoltStorage. The sharing happens one level down instead — this body
|
||||
// and the embedded store's are a few lines each around
|
||||
// issueops.DeleteInTx — and two wrappers over one body is still ONE vote,
|
||||
// which the conformance contract says out loud.
|
||||
//
|
||||
// A front door cannot construct this: the type is unexported and the accessor
|
||||
// is the only door.
|
||||
type deleter struct{ store *DoltStore }
|
||||
|
||||
var _ issueops.Deleter = (*deleter)(nil)
|
||||
|
||||
// Delete erases the request's ids.
|
||||
//
|
||||
// VALIDATION AND NORMALIZATION HAPPEN BEFORE THE TRANSACTION, so a malformed
|
||||
// request costs no database work and the body below sees a deduplicated,
|
||||
// trimmed id list. The refusals that need the graph — the missing id and the
|
||||
// dependents guard — happen inside it, because they are reads.
|
||||
//
|
||||
// A DRY RUN TAKES A READ TRANSACTION. It writes nothing by construction, so
|
||||
// giving it a write transaction and an empty commit would make a preview look
|
||||
// like a mutation to everything watching the store.
|
||||
//
|
||||
// THE VERSION-CONTROL ENTRY IS ONE PER DELETION, recorded here rather than in
|
||||
// the shared body because only this backend records one at all: the embedded
|
||||
// store commits outside the SQL transaction and the unit-of-work provider
|
||||
// labels its own. A deletion confined to the wisp tables touches only tables
|
||||
// this plane ignores, so DOLT_COMMIT finds nothing to commit and records no
|
||||
// entry — the "at most one" the role promises, not "exactly one".
|
||||
func (s *deleter) Delete(ctx context.Context, req issueops.DeleteRequest) (issueops.DeleteResult, error) {
|
||||
if err := workapi.ValidateDeleteRequest(req); err != nil {
|
||||
return issueops.DeleteResult{}, err
|
||||
}
|
||||
req.IDs = workapi.NormalizeDeleteIDs(req.IDs)
|
||||
|
||||
var result issueops.DeleteResult
|
||||
run := func(tx *sql.Tx) error {
|
||||
var err error
|
||||
result, err = storeops.DeleteInTx(ctx, tx, req)
|
||||
return err
|
||||
}
|
||||
if req.DryRun {
|
||||
if err := s.store.withReadTx(ctx, run); err != nil {
|
||||
return issueops.DeleteResult{}, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
if err := s.store.withWriteTx(ctx, func(tx *sql.Tx) error {
|
||||
if err := run(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if result.Deleted == 0 {
|
||||
return nil
|
||||
}
|
||||
// The same tables a sweep stages, because a delete IS a sweep of a
|
||||
// named set — plus the neighbor rewrite, which lands in `issues` and
|
||||
// is already on the list.
|
||||
for _, table := range sweptTables {
|
||||
_ = schema.DrainCall(ctx, tx, "CALL DOLT_ADD(?)", table)
|
||||
}
|
||||
msg := fmt.Sprintf("bd: delete %d issue(s)", result.Deleted)
|
||||
if err := schema.DrainCall(ctx, tx, "CALL DOLT_COMMIT('-m', ?, '--author', ?)",
|
||||
msg, s.store.commitAuthorString()); err != nil && !isDoltNothingToCommit(err) {
|
||||
return fmt.Errorf("dolt commit: %w", err)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return issueops.DeleteResult{}, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
85
internal/storage/dolt/deleter_contract_test.go
Normal file
85
internal/storage/dolt/deleter_contract_test.go
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
package dolt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/backend/conformance"
|
||||
)
|
||||
|
||||
// TestDeleterContract runs the Deleter contract against the server-backed
|
||||
// store, which reaches internal/storage/issueops.DeleteInTx through its own
|
||||
// write transaction and is the ONE wiring that records a version-control entry
|
||||
// for a deletion.
|
||||
//
|
||||
// The cases are subtests of one parent so the whole role suite shares one store
|
||||
// and one copy-on-write branch. That sharing is why every case namespaces its
|
||||
// seeds under fixture.IssuePrefix plus its own tag. setupTestStore already
|
||||
// marks the PARENT parallel; no subtest here calls t.Parallel, and
|
||||
// RecordsAtMostOneHistoryEntry takes a before/after delta that is only
|
||||
// meaningful while they run sequentially.
|
||||
func TestDeleterContract(t *testing.T) {
|
||||
fixture, ctx, cleanup := newDoltDeleterFixture(t, "del")
|
||||
defer cleanup()
|
||||
|
||||
t.Run("RefusesAMalformedRequest", func(t *testing.T) {
|
||||
conformance.RunDeleterRefusesAMalformedRequest(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RefusesAnAbsentID", func(t *testing.T) {
|
||||
conformance.RunDeleterRefusesAnAbsentID(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RefusesDependentsOutsideTheRequest", func(t *testing.T) {
|
||||
conformance.RunDeleterRefusesDependentsOutsideTheRequest(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ForceOrphansDependents", func(t *testing.T) {
|
||||
conformance.RunDeleterForceOrphansDependents(t, ctx, fixture)
|
||||
})
|
||||
t.Run("CascadeDeletesTheClosure", func(t *testing.T) {
|
||||
conformance.RunDeleterCascadeDeletesTheClosure(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ErasesAcrossBothPlanes", func(t *testing.T) {
|
||||
conformance.RunDeleterErasesAcrossBothPlanes(t, ctx, fixture)
|
||||
})
|
||||
t.Run("CollapsesDuplicateIDs", func(t *testing.T) {
|
||||
conformance.RunDeleterCollapsesDuplicateIDs(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RewritesReferencesInNeighbors", func(t *testing.T) {
|
||||
conformance.RunDeleterRewritesReferencesInNeighbors(t, ctx, fixture)
|
||||
})
|
||||
t.Run("DryRunChangesNothing", func(t *testing.T) {
|
||||
conformance.RunDeleterDryRunChangesNothing(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RecordsAtMostOneHistoryEntry", func(t *testing.T) {
|
||||
conformance.RunDeleterRecordsAtMostOneHistoryEntry(t, ctx, fixture)
|
||||
})
|
||||
t.Run("DoesNotMutateTheCallerRequest", func(t *testing.T) {
|
||||
conformance.RunDeleterDoesNotMutateTheCallerRequest(t, ctx, fixture)
|
||||
})
|
||||
}
|
||||
|
||||
// newDoltDeleterFixture composes the frozen role kit with this backend's
|
||||
// accessor.
|
||||
func newDoltDeleterFixture(t *testing.T, prefix string) (conformance.DeleterFixture, context.Context, func()) {
|
||||
t.Helper()
|
||||
store, storeCleanup := setupTestStore(t)
|
||||
ctx, cancel := testContext(t)
|
||||
stop := func() {
|
||||
cancel()
|
||||
storeCleanup()
|
||||
}
|
||||
deleter, err := store.Deleter()
|
||||
if err != nil {
|
||||
stop()
|
||||
t.Fatalf("Deleter(): %v", err)
|
||||
}
|
||||
kit := newDoltRoleFixtureKit(store, prefix)
|
||||
return conformance.DeleterFixture{
|
||||
IssuePrefix: kit.IssuePrefix,
|
||||
Deleter: deleter,
|
||||
CreateIssue: kit.CreateIssue,
|
||||
CreateWisp: kit.CreateWisp,
|
||||
AddDependency: kit.AddDependency,
|
||||
QueryScalar: kit.QueryScalar,
|
||||
CountHistory: kit.CountHistory,
|
||||
}, ctx, stop
|
||||
}
|
||||
|
|
@ -105,17 +105,6 @@ type DeleteIssuesParams struct {
|
|||
Cascade bool
|
||||
DryRun bool
|
||||
UpdateTextReferences bool
|
||||
|
||||
// EnforceCascadePolicy selects embedded-parity dependent handling
|
||||
// (issueops.DeleteIssuesInTx). When false — the legacy default used by the
|
||||
// proxied-server delete command, which always cascades — deletion expands to
|
||||
// all transitive dependents regardless of Cascade/Force. When true,
|
||||
// Cascade/Force choose the behavior:
|
||||
// Cascade=true → delete all transitive dependents
|
||||
// Cascade=false, Force=false → refuse if any external dependent exists
|
||||
// Cascade=false, Force=true → orphan external dependents (delete only IDs)
|
||||
EnforceCascadePolicy bool
|
||||
Force bool
|
||||
}
|
||||
|
||||
type DeleteIssuesResult struct {
|
||||
|
|
@ -124,9 +113,15 @@ type DeleteIssuesResult struct {
|
|||
LabelsCount int
|
||||
EventsCount int
|
||||
ReferencesUpdated int
|
||||
// OrphanedIssues lists external dependents left behind by a force delete
|
||||
// (Cascade=false, Force=true), or the blocking dependents reported with the
|
||||
// refusal error (Cascade=false, Force=false). Empty on the cascade path.
|
||||
// OrphanedIssues is NOT POPULATED BY ANY PATH TODAY, and is kept only
|
||||
// because `bd wisp gc --json` publishes it (always null) and this commit is
|
||||
// not changing that command's wire shape.
|
||||
//
|
||||
// It once described a force-delete policy this layer never implemented: the
|
||||
// two params that were supposed to select that policy were declared,
|
||||
// documented in detail and never read. The policy now lives in
|
||||
// issueops.Deleter, above the use case, and DeleteResult.Orphaned is where
|
||||
// the answer comes out.
|
||||
OrphanedIssues []string
|
||||
}
|
||||
|
||||
|
|
|
|||
54
internal/storage/embeddeddolt/deleter.go
Normal file
54
internal/storage/embeddeddolt/deleter.go
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
//go:build cgo
|
||||
|
||||
package embeddeddolt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
storeops "github.com/steveyegge/beads/internal/storage/issueops"
|
||||
"github.com/steveyegge/beads/internal/workapi"
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// Deleter returns the named-row erasure surface for this store.
|
||||
func (s *EmbeddedDoltStore) Deleter() (issueops.Deleter, error) {
|
||||
if s == nil {
|
||||
return nil, &storage.ErrUnsupported{Op: "Deleter", Backend: "nil"}
|
||||
}
|
||||
return &deleter{store: s}, nil
|
||||
}
|
||||
|
||||
// deleter erases named rows inside one connection's transaction.
|
||||
//
|
||||
// It is a sibling of the server-backed store's body rather than a shared
|
||||
// package for the reason that one gives: the work needs a TRANSACTION, which
|
||||
// storage.DoltStorage does not publish, so the sharing happens below both of
|
||||
// them at issueops.DeleteInTx. The two stores differ here only in how they
|
||||
// reach a transaction and in whether they record a version-control entry —
|
||||
// this one's commit runs outside the SQL transaction, so it records none.
|
||||
type deleter struct{ store *EmbeddedDoltStore }
|
||||
|
||||
var _ issueops.Deleter = (*deleter)(nil)
|
||||
|
||||
// Delete erases the request's ids. Validation and normalization happen before
|
||||
// the connection is opened, so a malformed request costs no database work.
|
||||
func (s *deleter) Delete(ctx context.Context, req issueops.DeleteRequest) (issueops.DeleteResult, error) {
|
||||
if err := workapi.ValidateDeleteRequest(req); err != nil {
|
||||
return issueops.DeleteResult{}, err
|
||||
}
|
||||
req.IDs = workapi.NormalizeDeleteIDs(req.IDs)
|
||||
|
||||
var result issueops.DeleteResult
|
||||
// commit = !DryRun: a preview writes nothing, so it must not take the
|
||||
// committing path — the same distinction Sweep draws here.
|
||||
if err := s.store.withConn(ctx, !req.DryRun, func(tx *sql.Tx) error {
|
||||
var err error
|
||||
result, err = storeops.DeleteInTx(ctx, tx, req)
|
||||
return err
|
||||
}); err != nil {
|
||||
return issueops.DeleteResult{}, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
77
internal/storage/embeddeddolt/deleter_contract_test.go
Normal file
77
internal/storage/embeddeddolt/deleter_contract_test.go
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
//go:build cgo
|
||||
|
||||
package embeddeddolt_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/backend/conformance"
|
||||
)
|
||||
|
||||
// TestDeleterContract runs the Deleter contract against the embedded store,
|
||||
// which hands back the SAME body the server-backed store does
|
||||
// (internal/storage/issueops.DeleteInTx) and differs only in how it reaches a
|
||||
// transaction and in that its commit runs outside one. That is what this wiring
|
||||
// catches; it is not an independent vote on the body.
|
||||
//
|
||||
// One environment for the whole suite: booting an embedded engine per case
|
||||
// would dominate the runtime, every case namespaces its seeds, and the history
|
||||
// delta needs the subtests sequential anyway.
|
||||
func TestDeleterContract(t *testing.T) {
|
||||
skipUnlessEmbeddedDolt(t)
|
||||
te := newTestEnv(t, "del")
|
||||
ctx := t.Context()
|
||||
fixture := newEmbeddedDeleterFixture(t, te, "del")
|
||||
|
||||
t.Run("RefusesAMalformedRequest", func(t *testing.T) {
|
||||
conformance.RunDeleterRefusesAMalformedRequest(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RefusesAnAbsentID", func(t *testing.T) {
|
||||
conformance.RunDeleterRefusesAnAbsentID(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RefusesDependentsOutsideTheRequest", func(t *testing.T) {
|
||||
conformance.RunDeleterRefusesDependentsOutsideTheRequest(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ForceOrphansDependents", func(t *testing.T) {
|
||||
conformance.RunDeleterForceOrphansDependents(t, ctx, fixture)
|
||||
})
|
||||
t.Run("CascadeDeletesTheClosure", func(t *testing.T) {
|
||||
conformance.RunDeleterCascadeDeletesTheClosure(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ErasesAcrossBothPlanes", func(t *testing.T) {
|
||||
conformance.RunDeleterErasesAcrossBothPlanes(t, ctx, fixture)
|
||||
})
|
||||
t.Run("CollapsesDuplicateIDs", func(t *testing.T) {
|
||||
conformance.RunDeleterCollapsesDuplicateIDs(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RewritesReferencesInNeighbors", func(t *testing.T) {
|
||||
conformance.RunDeleterRewritesReferencesInNeighbors(t, ctx, fixture)
|
||||
})
|
||||
t.Run("DryRunChangesNothing", func(t *testing.T) {
|
||||
conformance.RunDeleterDryRunChangesNothing(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RecordsAtMostOneHistoryEntry", func(t *testing.T) {
|
||||
conformance.RunDeleterRecordsAtMostOneHistoryEntry(t, ctx, fixture)
|
||||
})
|
||||
t.Run("DoesNotMutateTheCallerRequest", func(t *testing.T) {
|
||||
conformance.RunDeleterDoesNotMutateTheCallerRequest(t, ctx, fixture)
|
||||
})
|
||||
}
|
||||
|
||||
func newEmbeddedDeleterFixture(t *testing.T, te *testEnv, prefix string) conformance.DeleterFixture {
|
||||
t.Helper()
|
||||
deleter, err := te.store.Deleter()
|
||||
if err != nil {
|
||||
t.Fatalf("Deleter(): %v", err)
|
||||
}
|
||||
kit := newEmbeddedRoleFixtureKit(te, prefix)
|
||||
return conformance.DeleterFixture{
|
||||
IssuePrefix: kit.IssuePrefix,
|
||||
Deleter: deleter,
|
||||
CreateIssue: kit.CreateIssue,
|
||||
CreateWisp: kit.CreateWisp,
|
||||
AddDependency: kit.AddDependency,
|
||||
QueryScalar: kit.QueryScalar,
|
||||
CountHistory: kit.CountHistory,
|
||||
}
|
||||
}
|
||||
30
internal/storage/hook_deleter.go
Normal file
30
internal/storage/hook_deleter.go
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
package storage
|
||||
|
||||
import (
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// Deleter returns the inner store's named-row erasure surface.
|
||||
//
|
||||
// IT RECURSES UNWRAPPED, for the reason hook_sweeper.go gives at length and
|
||||
// which applies here unchanged: internal/hooks publishes on_create, on_update
|
||||
// and on_close, and a deletion is none of them. Firing on_update for a row that
|
||||
// no longer exists would hand a user's script an id it cannot read back, and
|
||||
// the result this role returns carries counts rather than rows, so there is no
|
||||
// issue to hand a hook script even if one existed.
|
||||
//
|
||||
// THE ONE CASE THAT LOOKS LIKE AN EXCEPTION IS NOT. A deletion rewrites its
|
||||
// neighbors' text, and those rows survive an update — so an on_update hook
|
||||
// could in principle fire for them. It does not, deliberately: the rewrite is
|
||||
// a consequence of the deletion rather than an update a user asked for, and a
|
||||
// `bd delete` of one bead that fired a subprocess per neighbor would be a new
|
||||
// failure mode wearing a feature's clothes. The direct CLI route this role
|
||||
// replaces fired no hook for those updates either.
|
||||
//
|
||||
// So the accessor EXISTS on this decorator — declared, never inherited, which
|
||||
// the reflection test in role_accessor_decorator_test.go asserts — and adds no
|
||||
// layer. If a delete event ever joins the hook vocabulary, this file is where
|
||||
// it lands.
|
||||
func (h *HookFiringStore) Deleter() (issueops.Deleter, error) {
|
||||
return h.inner.Deleter()
|
||||
}
|
||||
|
|
@ -7,6 +7,8 @@ import (
|
|||
|
||||
"github.com/steveyegge/beads/internal/storage"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/workapi"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// deleteBatchSize controls the maximum number of IDs per IN-clause query
|
||||
|
|
@ -99,56 +101,31 @@ func DeleteIssuesInTx(ctx context.Context, tx *sql.Tx, ids []string, cascade boo
|
|||
for id := range allToDelete {
|
||||
expandedRegularIDs = append(expandedRegularIDs, id)
|
||||
}
|
||||
} else if !force {
|
||||
for i := 0; i < len(regularIDs); i += deleteBatchSize {
|
||||
end := i + deleteBatchSize
|
||||
if end > len(regularIDs) {
|
||||
end = len(regularIDs)
|
||||
}
|
||||
batch := regularIDs[i:end]
|
||||
inClause, args := buildSQLInClause(batch)
|
||||
|
||||
externalBySource := make(map[string][]string)
|
||||
for _, depTable := range []string{"dependencies", "wisp_dependencies"} {
|
||||
rows, err := tx.QueryContext(ctx,
|
||||
fmt.Sprintf(`SELECT %s AS depends_on_id, issue_id FROM %s WHERE %s`, DepTargetExpr, depTable, depTargetIn("", inClause)),
|
||||
args...)
|
||||
if err != nil {
|
||||
if optionalBlockedTable(depTable) && isTableNotExistError(err) {
|
||||
continue
|
||||
}
|
||||
return nil, fmt.Errorf("check dependents from %s: %w", depTable, err)
|
||||
}
|
||||
|
||||
for rows.Next() {
|
||||
var depOnID, issueID string
|
||||
if err := rows.Scan(&depOnID, &issueID); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, fmt.Errorf("scan dependent: %w", err)
|
||||
}
|
||||
if !idSet[issueID] {
|
||||
externalBySource[depOnID] = append(externalBySource[depOnID], issueID)
|
||||
}
|
||||
}
|
||||
_ = rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate dependents from %s: %w", depTable, err)
|
||||
}
|
||||
}
|
||||
|
||||
for _, id := range batch {
|
||||
if deps, ok := externalBySource[id]; ok {
|
||||
result.OrphanedIssues = deps
|
||||
return result, fmt.Errorf("issue %s has dependents not in deletion set; use --cascade to delete them or --force to orphan them", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
orphans, err := findExternalDependentsBatchedInTx(ctx, tx, regularIDs, idSet)
|
||||
// One scan of the dependency planes answers both modes: the guard
|
||||
// needs to know WHICH id is blocked, and the forced path needs the
|
||||
// union of what it orphans. ExternalDependentsBySourceInTx gives the
|
||||
// per-source shape both read.
|
||||
external, err := ExternalDependentsBySourceInTx(ctx, tx, regularIDs, idSet)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get dependents: %w", err)
|
||||
}
|
||||
result.OrphanedIssues = orphans
|
||||
if !force {
|
||||
for _, id := range regularIDs {
|
||||
if deps := external[id]; len(deps) > 0 {
|
||||
result.OrphanedIssues = deps
|
||||
return result, &publicops.DependentsOutsideRequestError{IssueID: id, Dependents: deps}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
orphans := make(map[string]bool)
|
||||
for _, deps := range external {
|
||||
for _, id := range deps {
|
||||
orphans[id] = true
|
||||
}
|
||||
}
|
||||
result.OrphanedIssues = workapi.SortedDeleteIDs(orphans)
|
||||
}
|
||||
}
|
||||
|
||||
cascadeWispIDs, finalRegularIDs, err := PartitionWispIDsInTx(ctx, tx, expandedRegularIDs)
|
||||
|
|
@ -340,54 +317,6 @@ func FindAllDependentsInTx(ctx context.Context, tx DBTX, ids []string) (map[stri
|
|||
return result, nil
|
||||
}
|
||||
|
||||
// findExternalDependentsBatchedInTx finds all dependents of the given IDs
|
||||
// that are NOT in the idSet.
|
||||
//
|
||||
//nolint:gosec // G201: inClause contains only ? placeholders
|
||||
func findExternalDependentsBatchedInTx(ctx context.Context, tx *sql.Tx, ids []string, idSet map[string]bool) ([]string, error) {
|
||||
orphanSet := make(map[string]bool)
|
||||
for i := 0; i < len(ids); i += deleteBatchSize {
|
||||
end := i + deleteBatchSize
|
||||
if end > len(ids) {
|
||||
end = len(ids)
|
||||
}
|
||||
batch := ids[i:end]
|
||||
inClause, args := buildSQLInClause(batch)
|
||||
|
||||
for _, depTable := range []string{"dependencies", "wisp_dependencies"} {
|
||||
rows, err := tx.QueryContext(ctx,
|
||||
fmt.Sprintf(`SELECT issue_id FROM %s WHERE %s`, depTable, depTargetIn("", inClause)),
|
||||
args...)
|
||||
if err != nil {
|
||||
if optionalBlockedTable(depTable) && isTableNotExistError(err) {
|
||||
continue
|
||||
}
|
||||
return nil, fmt.Errorf("query dependents from %s: %w", depTable, err)
|
||||
}
|
||||
for rows.Next() {
|
||||
var depID string
|
||||
if err := rows.Scan(&depID); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, fmt.Errorf("scan dependent: %w", err)
|
||||
}
|
||||
if !idSet[depID] {
|
||||
orphanSet[depID] = true
|
||||
}
|
||||
}
|
||||
_ = rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate dependents from %s: %w", depTable, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result := make([]string, 0, len(orphanSet))
|
||||
for id := range orphanSet {
|
||||
result = append(result, id)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
//nolint:gosec // G201: table is selected by callers from fixed issue/wisp auxiliary tables.
|
||||
func CountRowsForIssueIDsInTx(ctx context.Context, tx DBTX, table string, ids []string) (int, error) {
|
||||
total := 0
|
||||
|
|
|
|||
340
internal/storage/issueops/delete_role.go
Normal file
340
internal/storage/issueops/delete_role.go
Normal file
|
|
@ -0,0 +1,340 @@
|
|||
package issueops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"regexp"
|
||||
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/workapi"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// DeleteInTx is the store-backed body behind issueops.Deleter: the whole of
|
||||
// `bd delete` from the existence probe to the reference rewrite, inside ONE
|
||||
// transaction.
|
||||
//
|
||||
// It lives here rather than in an importable internal/workapi/store<role>
|
||||
// package for the reason SweepInTx does: the work is several reads and several
|
||||
// writes that must see one snapshot, and storage.DoltStorage publishes
|
||||
// methods, not transactions. The two Dolt-backed stores share this body and
|
||||
// differ only in how they reach a transaction, so they are ONE vote and the
|
||||
// unit-of-work provider is the second. There is nothing here a front door
|
||||
// could construct — the function takes a transaction — so no depguard entry is
|
||||
// needed to keep it out of cmd/bd.
|
||||
//
|
||||
// It assumes a request already refused by workapi.ValidateDeleteRequest and
|
||||
// already normalized by workapi.NormalizeDeleteIDs. The accessors do both
|
||||
// BEFORE opening a transaction, so a malformed request costs no database work.
|
||||
//
|
||||
// THE REWRITE IS INSIDE THE TRANSACTION, and that is what this body adds over
|
||||
// the code it replaces. The direct CLI route's batch path deleted the rows in
|
||||
// one transaction and then rewrote the neighbors' text through the store
|
||||
// afterwards, discarding each update's error; a failure between the two left a
|
||||
// workspace whose rows were gone and whose descriptions still cited them.
|
||||
func DeleteInTx(ctx context.Context, tx *sql.Tx, req publicops.DeleteRequest) (publicops.DeleteResult, error) {
|
||||
ids := req.IDs
|
||||
result := publicops.DeleteResult{DryRun: req.DryRun}
|
||||
|
||||
// The existence probe comes FIRST, so `bd delete typo real` reports the
|
||||
// typo rather than whatever the graph says about the id that resolved.
|
||||
// It doubles as the hydration the rewrite needs later: an id present here
|
||||
// is a row in one of the two planes.
|
||||
wispSet, err := WispIDSetInTx(ctx, tx, ids)
|
||||
if err != nil {
|
||||
return publicops.DeleteResult{}, fmt.Errorf("delete: classify planes: %w", err)
|
||||
}
|
||||
found, err := GetIssuesByIDsInTx(ctx, tx, ids, wispSet)
|
||||
if err != nil {
|
||||
return publicops.DeleteResult{}, fmt.Errorf("delete: resolve ids: %w", err)
|
||||
}
|
||||
present := make(map[string]bool, len(found))
|
||||
for _, issue := range found {
|
||||
if issue != nil {
|
||||
present[issue.ID] = true
|
||||
}
|
||||
}
|
||||
var missing []string
|
||||
for _, id := range ids {
|
||||
if !present[id] {
|
||||
missing = append(missing, id)
|
||||
}
|
||||
}
|
||||
if len(missing) > 0 {
|
||||
return publicops.DeleteResult{}, &publicops.NotFoundError{IDs: missing}
|
||||
}
|
||||
|
||||
idSet := make(map[string]bool, len(ids))
|
||||
for _, id := range ids {
|
||||
idSet[id] = true
|
||||
}
|
||||
|
||||
// The guard runs only when the request did not already say what to do
|
||||
// about dependents. Under Cascade there is nothing outside the set by
|
||||
// construction, which is why the expansion below is not asked about it.
|
||||
if !req.Cascade {
|
||||
_, regularIDs := partitionByWispSet(ids, wispSet)
|
||||
external, err := ExternalDependentsBySourceInTx(ctx, tx, regularIDs, idSet)
|
||||
if err != nil {
|
||||
return publicops.DeleteResult{}, fmt.Errorf("delete: check dependents: %w", err)
|
||||
}
|
||||
if !req.Force {
|
||||
// Request order, so the id a caller is told about is stable
|
||||
// across runs and across backends.
|
||||
for _, id := range ids {
|
||||
if deps := external[id]; len(deps) > 0 {
|
||||
return publicops.DeleteResult{}, &publicops.DependentsOutsideRequestError{
|
||||
IssueID: id,
|
||||
Dependents: deps,
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
orphaned := make(map[string]bool)
|
||||
for _, deps := range external {
|
||||
for _, id := range deps {
|
||||
orphaned[id] = true
|
||||
}
|
||||
}
|
||||
result.Orphaned = workapi.SortedDeleteIDs(orphaned)
|
||||
}
|
||||
}
|
||||
|
||||
// The neighborhood is read BEFORE the deletion, because after it the
|
||||
// edges that identify a neighbor are gone. It is read against the whole
|
||||
// deletion set — the cascade closure, not just the named ids — so a row
|
||||
// citing a cascade-deleted id is rewritten too.
|
||||
deletionSet := ids
|
||||
if req.Cascade {
|
||||
closure, err := FindAllDependentsInTx(ctx, tx, ids)
|
||||
if err != nil {
|
||||
return publicops.DeleteResult{}, fmt.Errorf("delete: expand cascade: %w", err)
|
||||
}
|
||||
deletionSet = make([]string, 0, len(closure))
|
||||
for id := range closure {
|
||||
deletionSet = append(deletionSet, id)
|
||||
}
|
||||
}
|
||||
neighbors, err := deleteNeighborsInTx(ctx, tx, deletionSet)
|
||||
if err != nil {
|
||||
return publicops.DeleteResult{}, err
|
||||
}
|
||||
|
||||
// force=true unconditionally: this body has ALREADY answered the guard
|
||||
// question above and holds the orphan list it produced, so letting the
|
||||
// shared batch delete ask it a second time would be one more scan of the
|
||||
// dependency tables on the path that is about to write.
|
||||
deleted, err := DeleteIssuesInTx(ctx, tx, ids, req.Cascade, true, req.DryRun)
|
||||
if err != nil {
|
||||
return publicops.DeleteResult{}, err
|
||||
}
|
||||
result.Deleted = deleted.DeletedCount
|
||||
result.Dependencies = deleted.DependenciesCount
|
||||
result.Labels = deleted.LabelsCount
|
||||
result.Events = deleted.EventsCount
|
||||
|
||||
if req.DryRun {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
rewritten, err := RewriteDeletedReferencesInTx(ctx, tx, deletionSet, neighbors, req.Actor)
|
||||
if err != nil {
|
||||
return publicops.DeleteResult{}, err
|
||||
}
|
||||
result.ReferencesUpdated = rewritten
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ExternalDependentsBySourceInTx reports, for each of ids, the DIRECT
|
||||
// dependents that idSet does not contain — the rows a forced delete orphans
|
||||
// and an unforced one refuses over.
|
||||
//
|
||||
// It reads both dependency planes and skips a missing wisp plane, the way
|
||||
// every other cross-plane read here does. The per-source shape is what lets
|
||||
// the unforced refusal name ONE blocked id instead of a flat union that
|
||||
// answers "something is blocked".
|
||||
//
|
||||
//nolint:gosec // G201: inClause contains only ? placeholders
|
||||
func ExternalDependentsBySourceInTx(ctx context.Context, tx DBTX, ids []string, idSet map[string]bool) (map[string][]string, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
bySource := make(map[string]map[string]bool)
|
||||
for i := 0; i < len(ids); i += deleteBatchSize {
|
||||
end := i + deleteBatchSize
|
||||
if end > len(ids) {
|
||||
end = len(ids)
|
||||
}
|
||||
inClause, args := buildSQLInClause(ids[i:end])
|
||||
|
||||
for _, depTable := range []string{"dependencies", "wisp_dependencies"} {
|
||||
rows, err := tx.QueryContext(ctx,
|
||||
fmt.Sprintf(`SELECT %s AS depends_on_id, issue_id FROM %s WHERE %s`,
|
||||
DepTargetExpr, depTable, depTargetIn("", inClause)),
|
||||
args...)
|
||||
if err != nil {
|
||||
if optionalBlockedTable(depTable) && isTableNotExistError(err) {
|
||||
continue
|
||||
}
|
||||
return nil, fmt.Errorf("query dependents from %s: %w", depTable, err)
|
||||
}
|
||||
for rows.Next() {
|
||||
var target, dependent string
|
||||
if err := rows.Scan(&target, &dependent); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, fmt.Errorf("scan dependent: %w", err)
|
||||
}
|
||||
if idSet[dependent] {
|
||||
continue
|
||||
}
|
||||
if bySource[target] == nil {
|
||||
bySource[target] = make(map[string]bool)
|
||||
}
|
||||
bySource[target][dependent] = true
|
||||
}
|
||||
_ = rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate dependents from %s: %w", depTable, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
out := make(map[string][]string, len(bySource))
|
||||
for target, dependents := range bySource {
|
||||
out[target] = workapi.SortedDeleteIDs(dependents)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// deleteNeighborsInTx hydrates the SURVIVING rows joined to the deletion set
|
||||
// by a dependency edge in either direction — the rows whose text the deletion
|
||||
// rewrites.
|
||||
//
|
||||
// One query per plane over the whole set rather than the two per deleted id
|
||||
// the CLI route used, because the neighborhood of a `--from-file` batch is
|
||||
// asked for once here and the route asked for it 2N times.
|
||||
//
|
||||
//nolint:gosec // G201: inClause contains only ? placeholders
|
||||
func deleteNeighborsInTx(ctx context.Context, tx DBTX, ids []string) ([]*types.Issue, error) {
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
deleting := make(map[string]bool, len(ids))
|
||||
for _, id := range ids {
|
||||
deleting[id] = true
|
||||
}
|
||||
|
||||
neighborIDs := make(map[string]bool)
|
||||
for i := 0; i < len(ids); i += deleteBatchSize {
|
||||
end := i + deleteBatchSize
|
||||
if end > len(ids) {
|
||||
end = len(ids)
|
||||
}
|
||||
inClause, args := buildSQLInClause(ids[i:end])
|
||||
doubled := append(append([]interface{}{}, args...), args...)
|
||||
|
||||
for _, depTable := range []string{"dependencies", "wisp_dependencies"} {
|
||||
rows, err := tx.QueryContext(ctx,
|
||||
fmt.Sprintf(`SELECT issue_id, %s AS depends_on_id FROM %s WHERE issue_id IN (%s) OR %s`,
|
||||
DepTargetExpr, depTable, inClause, depTargetIn("", inClause)),
|
||||
doubled...)
|
||||
if err != nil {
|
||||
if optionalBlockedTable(depTable) && isTableNotExistError(err) {
|
||||
continue
|
||||
}
|
||||
return nil, fmt.Errorf("query neighbors from %s: %w", depTable, err)
|
||||
}
|
||||
for rows.Next() {
|
||||
var source, target string
|
||||
if err := rows.Scan(&source, &target); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, fmt.Errorf("scan neighbor: %w", err)
|
||||
}
|
||||
for _, candidate := range [2]string{source, target} {
|
||||
if candidate == "" || deleting[candidate] {
|
||||
continue
|
||||
}
|
||||
neighborIDs[candidate] = true
|
||||
}
|
||||
}
|
||||
_ = rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("iterate neighbors from %s: %w", depTable, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(neighborIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Sorted so the rewrite touches rows in a stable order, which is what
|
||||
// makes a partially-applied failure reproducible.
|
||||
hydrate := workapi.SortedDeleteIDs(neighborIDs)
|
||||
// An `external:` target and a target belonging to another repository name
|
||||
// no row here; GetIssuesByIDsInTx simply does not return them.
|
||||
issues, err := GetIssuesByIDsInTx(ctx, tx, hydrate, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("hydrate neighbors: %w", err)
|
||||
}
|
||||
return issues, nil
|
||||
}
|
||||
|
||||
// RewriteDeletedReferencesInTx replaces every word-boundary occurrence of a
|
||||
// deleted id with `[deleted:<id>]` in each neighbor's description, notes,
|
||||
// design and acceptance criteria, and reports how many ROWS it changed.
|
||||
//
|
||||
// Exported because the unit-of-work body needs the same rule and neither
|
||||
// implementation may own it: a route that spelled the pattern differently
|
||||
// would rewrite a different set of citations for the same deletion.
|
||||
func RewriteDeletedReferencesInTx(ctx context.Context, tx DBTX, deletedIDs []string, neighbors []*types.Issue, actor string) (int, error) {
|
||||
if len(neighbors) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
touched := make(map[string]bool)
|
||||
for _, id := range deletedIDs {
|
||||
re := DeletedReferencePattern(id)
|
||||
replacement := `$1[deleted:` + id + `]$3`
|
||||
for _, neighbor := range neighbors {
|
||||
if neighbor == nil {
|
||||
continue
|
||||
}
|
||||
updates := make(map[string]interface{})
|
||||
for _, field := range []struct {
|
||||
column string
|
||||
value *string
|
||||
}{
|
||||
{"description", &neighbor.Description},
|
||||
{"notes", &neighbor.Notes},
|
||||
{"design", &neighbor.Design},
|
||||
{"acceptance_criteria", &neighbor.AcceptanceCriteria},
|
||||
} {
|
||||
if *field.value == "" || !re.MatchString(*field.value) {
|
||||
continue
|
||||
}
|
||||
rewritten := re.ReplaceAllString(*field.value, replacement)
|
||||
updates[field.column] = rewritten
|
||||
// Write the rewrite back onto the in-memory row so a second
|
||||
// deleted id in the same field sees the first one's result
|
||||
// rather than re-reading the original.
|
||||
*field.value = rewritten
|
||||
}
|
||||
if len(updates) == 0 {
|
||||
continue
|
||||
}
|
||||
if _, err := UpdateIssueInTx(ctx, tx, neighbor.ID, updates, actor); err != nil {
|
||||
return 0, fmt.Errorf("rewrite references in %s: %w", neighbor.ID, err)
|
||||
}
|
||||
touched[neighbor.ID] = true
|
||||
}
|
||||
}
|
||||
return len(touched), nil
|
||||
}
|
||||
|
||||
// DeletedReferencePattern is the citation rule, in one place: a literal id at
|
||||
// ASCII word boundaries, where a word character includes the hyphen an id is
|
||||
// full of. It matches `be-1` in "see (be-1)." and not inside `xbe-1` or
|
||||
// `be-12`.
|
||||
func DeletedReferencePattern(id string) *regexp.Regexp {
|
||||
return regexp.MustCompile(`(^|[^A-Za-z0-9_-])(` + regexp.QuoteMeta(id) + `)($|[^A-Za-z0-9_-])`)
|
||||
}
|
||||
|
|
@ -29,6 +29,7 @@ var roleAccessorNames = []string{
|
|||
"ReadyCounter",
|
||||
"Querier",
|
||||
"Sweeper",
|
||||
"Deleter",
|
||||
"Commenter",
|
||||
"ReadyClaimer",
|
||||
"BatchCloser",
|
||||
|
|
@ -94,6 +95,7 @@ type roleAccessorStore struct {
|
|||
readyCounter issueops.ReadyCounter
|
||||
querier issueops.Querier
|
||||
sweeper issueops.Sweeper
|
||||
deleter issueops.Deleter
|
||||
err error
|
||||
}
|
||||
|
||||
|
|
@ -118,6 +120,7 @@ func newRoleAccessorStore() *roleAccessorStore {
|
|||
readyCounter: sentinel,
|
||||
querier: sentinel,
|
||||
sweeper: sentinel,
|
||||
deleter: sentinel,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -150,6 +153,9 @@ func (s *roleAccessorStore) Querier() (issueops.Querier, error) { return s.queri
|
|||
func (s *roleAccessorStore) Sweeper() (issueops.Sweeper, error) {
|
||||
return s.sweeper, s.err
|
||||
}
|
||||
func (s *roleAccessorStore) Deleter() (issueops.Deleter, error) {
|
||||
return s.deleter, s.err
|
||||
}
|
||||
func (s *roleAccessorStore) ReadyClaimer() (issueops.ReadyClaimer, error) {
|
||||
return s.claimer, s.err
|
||||
}
|
||||
|
|
@ -238,6 +244,10 @@ func (*roleAccessorSentinel) Query(context.Context, issueops.QueryRequest) (issu
|
|||
return issueops.IssuePage{}, nil
|
||||
}
|
||||
|
||||
func (*roleAccessorSentinel) Delete(context.Context, issueops.DeleteRequest) (issueops.DeleteResult, error) {
|
||||
return issueops.DeleteResult{}, nil
|
||||
}
|
||||
|
||||
func (*roleAccessorSentinel) Sweep(context.Context, issueops.SweepRequest) (issueops.SweepResult, error) {
|
||||
return issueops.SweepResult{}, nil
|
||||
}
|
||||
|
|
@ -312,6 +322,10 @@ func TestHookFiringStoreWrapsTheWriteRolesAndPassesTheReadsThrough(t *testing.T)
|
|||
// fire and a swept row is gone, so hook_sweeper.go recurses. Asserting
|
||||
// it here is what keeps that a decision.
|
||||
{"Sweeper", func() (any, error) { return store.Sweeper() }, inner.sweeper, false},
|
||||
// The other WRITE role in the unwrapped column, for the same reason:
|
||||
// hook_deleter.go recurses because the hook vocabulary has no name for
|
||||
// a deletion, not because the role reads.
|
||||
{"Deleter", func() (any, error) { return store.Deleter() }, inner.deleter, false},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
surface, err := test.got()
|
||||
|
|
@ -360,6 +374,7 @@ func TestHookFiringStoreRoleAccessorsPropagateInnerErrors(t *testing.T) {
|
|||
{"ReadyCounter", func() (any, error) { return store.ReadyCounter() }},
|
||||
{"Querier", func() (any, error) { return store.Querier() }},
|
||||
{"Sweeper", func() (any, error) { return store.Sweeper() }},
|
||||
{"Deleter", func() (any, error) { return store.Deleter() }},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if _, err := test.got(); !errors.Is(err, want) {
|
||||
|
|
|
|||
|
|
@ -245,6 +245,19 @@ type Storage interface {
|
|||
// update and close), and the rows a sweep would name it with are gone.
|
||||
// See hook_sweeper.go.
|
||||
Sweeper() (issueops.Sweeper, error)
|
||||
// Deleter returns the named-row erasure surface for this store —
|
||||
// `bd delete`. Its own role rather than a Sweeper mode because Sweeper
|
||||
// erases a set the caller DESCRIBED and this one erases rows the caller
|
||||
// NAMED, which is what decides where each one's safety lives: a
|
||||
// description can be accidentally too wide, so Sweeper carries a
|
||||
// require-a-filter gate, while a list of ids cannot, so this one's guard is
|
||||
// about the graph — a named row with a dependent the request did not name
|
||||
// is refused unless the caller says cascade or force.
|
||||
//
|
||||
// Its hook decorator recurses UNWRAPPED for the same reason Sweeper's
|
||||
// does: there is no on_delete hook to fire and the rows are gone. See
|
||||
// hook_deleter.go.
|
||||
Deleter() (issueops.Deleter, error)
|
||||
|
||||
// Issue CRUD
|
||||
CreateIssue(ctx context.Context, issue *types.Issue, actor string) error
|
||||
|
|
|
|||
223
internal/storage/uow/deleter.go
Normal file
223
internal/storage/uow/deleter.go
Normal file
|
|
@ -0,0 +1,223 @@
|
|||
package uow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/steveyegge/beads/internal/storage/dberrors"
|
||||
"github.com/steveyegge/beads/internal/storage/domain"
|
||||
"github.com/steveyegge/beads/internal/types"
|
||||
"github.com/steveyegge/beads/internal/workapi"
|
||||
publicops "github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// DeleterSource is the capability accessor a unit-of-work provider offers for
|
||||
// the named-row erasure role, the sibling of SweeperSource and CounterSource. A
|
||||
// consumer holding a provider by interface asks for the role here instead of
|
||||
// reaching for a constructor.
|
||||
type DeleterSource interface {
|
||||
Deleter() (publicops.Deleter, error)
|
||||
}
|
||||
|
||||
// deleter erases named rows through a unit of work.
|
||||
type deleter struct {
|
||||
provider UnitOfWorkProvider
|
||||
}
|
||||
|
||||
// Deleter returns the named-row erasure surface for this provider.
|
||||
func (p *doltSQLProvider) Deleter() (publicops.Deleter, error) {
|
||||
return NewDeleter(p)
|
||||
}
|
||||
|
||||
// NewDeleter constructs a public deleter backed by provider.
|
||||
func NewDeleter(provider UnitOfWorkProvider) (publicops.Deleter, error) {
|
||||
if isNilUnitOfWorkProvider(provider) {
|
||||
return nil, fmt.Errorf("new deleter: unit-of-work provider must not be nil")
|
||||
}
|
||||
return &deleter{provider: provider}, nil
|
||||
}
|
||||
|
||||
var _ publicops.Deleter = (*deleter)(nil)
|
||||
|
||||
// Delete erases the request's ids inside ONE unit of work.
|
||||
//
|
||||
// This is the genuinely separate body: the two store backends share
|
||||
// issueops.DeleteInTx, and this one reaches the same questions through the
|
||||
// domain use cases. What it must NOT do differently is which rows go and which
|
||||
// requests are refused — the id normalization and the request rules run through
|
||||
// the same internal/workapi functions the shared body runs, and the two
|
||||
// answers that need the graph are asserted equal by the conformance contract.
|
||||
//
|
||||
// THE GUARD IS HERE RATHER THAN IN THE USE CASE, and that is a deliberate
|
||||
// placement. domain.IssueUseCase.DeleteIssues already selects the right SET for
|
||||
// both modes — Cascade expands to the transitive dependents, no Cascade deletes
|
||||
// exactly what it was handed and orphans the rest — but it has never refused
|
||||
// anything, and the proxied route papered over that by hardcoding Cascade for
|
||||
// every call. The refusal belongs above the use case with the rest of the
|
||||
// role's policy, so a future use-case caller cannot inherit the capability and
|
||||
// miss the guard.
|
||||
//
|
||||
// A DRY RUN TAKES A READ-ONLY UNIT OF WORK: it writes nothing, so it must not
|
||||
// take the committing path and leave a history entry describing a preview.
|
||||
func (d *deleter) Delete(ctx context.Context, req publicops.DeleteRequest) (publicops.DeleteResult, error) {
|
||||
if err := workapi.ValidateDeleteRequest(req); err != nil {
|
||||
return publicops.DeleteResult{}, err
|
||||
}
|
||||
req.IDs = workapi.NormalizeDeleteIDs(req.IDs)
|
||||
|
||||
if req.DryRun {
|
||||
return RunTxRead(ctx, d.provider, func(ctx context.Context, uw UnitOfWork) (publicops.DeleteResult, error) {
|
||||
return deleteInUOW(ctx, uw, req)
|
||||
})
|
||||
}
|
||||
return RunTxResult(ctx, d.provider, func(ctx context.Context, uw UnitOfWork) (publicops.DeleteResult, string, error) {
|
||||
result, err := deleteInUOW(ctx, uw, req)
|
||||
if err != nil || result.Deleted == 0 {
|
||||
// A deletion that removed nothing labels nothing: the role
|
||||
// promises at most one history entry per call and none for a
|
||||
// no-op.
|
||||
return result, "", err
|
||||
}
|
||||
return result, fmt.Sprintf("bd: delete %d issue(s)", result.Deleted), nil
|
||||
})
|
||||
}
|
||||
|
||||
// deleteInUOW is the whole deletion on one unit of work, shared by the preview
|
||||
// path and the committing one so the two cannot answer differently — which on
|
||||
// this role is the point rather than tidiness: issueops.Deleter promises that a
|
||||
// dry run refuses exactly where the real run refuses.
|
||||
func deleteInUOW(ctx context.Context, uw UnitOfWork, req publicops.DeleteRequest) (publicops.DeleteResult, error) {
|
||||
issueUC := uw.IssueUseCase()
|
||||
result := publicops.DeleteResult{DryRun: req.DryRun}
|
||||
|
||||
// The existence probe comes FIRST, so a request naming a typo reports the
|
||||
// typo rather than whatever the graph says about the ids that resolved.
|
||||
present := make(map[string]bool, len(req.IDs))
|
||||
for _, load := range []func(context.Context, []string) ([]*types.Issue, error){
|
||||
issueUC.GetIssuesByIDs,
|
||||
issueUC.GetWispsByIDs,
|
||||
} {
|
||||
rows, err := load(ctx, req.IDs)
|
||||
if err != nil {
|
||||
return publicops.DeleteResult{}, fmt.Errorf("delete: resolve ids: %w", err)
|
||||
}
|
||||
for _, row := range rows {
|
||||
if row != nil {
|
||||
present[row.ID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
var missing []string
|
||||
for _, id := range req.IDs {
|
||||
if !present[id] {
|
||||
missing = append(missing, id)
|
||||
}
|
||||
}
|
||||
if len(missing) > 0 {
|
||||
return publicops.DeleteResult{}, &publicops.NotFoundError{IDs: missing}
|
||||
}
|
||||
|
||||
// The guard runs only when the request did not already say what to do
|
||||
// about dependents. Under Cascade there is nothing outside the set by
|
||||
// construction.
|
||||
if !req.Cascade {
|
||||
idSet := make(map[string]bool, len(req.IDs))
|
||||
for _, id := range req.IDs {
|
||||
idSet[id] = true
|
||||
}
|
||||
external, err := externalDependentsBySourceInUOW(ctx, uw, req.IDs, idSet)
|
||||
if err != nil {
|
||||
return publicops.DeleteResult{}, err
|
||||
}
|
||||
if !req.Force {
|
||||
// Request order, so the id a caller is told about is stable
|
||||
// across runs and across backends.
|
||||
for _, id := range req.IDs {
|
||||
if deps := external[id]; len(deps) > 0 {
|
||||
return publicops.DeleteResult{}, &publicops.DependentsOutsideRequestError{
|
||||
IssueID: id,
|
||||
Dependents: deps,
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
orphaned := make(map[string]bool)
|
||||
for _, deps := range external {
|
||||
for _, id := range deps {
|
||||
orphaned[id] = true
|
||||
}
|
||||
}
|
||||
result.Orphaned = workapi.SortedDeleteIDs(orphaned)
|
||||
}
|
||||
}
|
||||
|
||||
deleted, err := issueUC.DeleteIssues(ctx, domain.DeleteIssuesParams{
|
||||
IDs: req.IDs,
|
||||
Cascade: req.Cascade,
|
||||
DryRun: req.DryRun,
|
||||
// A preview rewrites nothing, so it must not ask for the rewrite; the
|
||||
// use case would stop short of it anyway, and asking would make the
|
||||
// intent depend on that.
|
||||
UpdateTextReferences: !req.DryRun,
|
||||
}, req.Actor)
|
||||
if err != nil {
|
||||
return publicops.DeleteResult{}, err
|
||||
}
|
||||
result.Deleted = deleted.DeletedCount
|
||||
result.Dependencies = deleted.DependenciesCount
|
||||
result.Labels = deleted.LabelsCount
|
||||
result.Events = deleted.EventsCount
|
||||
result.ReferencesUpdated = deleted.ReferencesUpdated
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// externalDependentsBySourceInUOW reports, for each of ids, the DIRECT
|
||||
// dependents idSet does not contain — the rows a forced delete orphans and an
|
||||
// unforced one refuses over.
|
||||
//
|
||||
// It asks both planes, the way the shared store body's
|
||||
// issueops.ExternalDependentsBySourceInTx does, because an edge from a wisp
|
||||
// into an issue lives in the wisp table and a guard that missed it would
|
||||
// silently orphan the wisp.
|
||||
func externalDependentsBySourceInUOW(
|
||||
ctx context.Context, uw UnitOfWork, ids []string, idSet map[string]bool,
|
||||
) (map[string][]string, error) {
|
||||
depUC := uw.DependencyUseCase()
|
||||
bySource := make(map[string]map[string]bool)
|
||||
|
||||
for _, plane := range []struct {
|
||||
list func(context.Context, []string, domain.DepListFilter) (domain.DepBulkResult, error)
|
||||
optional bool
|
||||
}{
|
||||
{list: depUC.ListByIssueIDs},
|
||||
// The wisp plane is optional the way every other cross-plane read here
|
||||
// treats it: a workspace whose schema predates it has no table, and
|
||||
// that is not a failed guard.
|
||||
{list: depUC.ListByWispIDs, optional: true},
|
||||
} {
|
||||
res, err := plane.list(ctx, ids, domain.DepListFilter{Direction: domain.DepDirectionIn})
|
||||
if err != nil {
|
||||
if plane.optional && dberrors.IsTableNotExist(err) {
|
||||
continue
|
||||
}
|
||||
return nil, fmt.Errorf("delete: check dependents: %w", err)
|
||||
}
|
||||
for target, edges := range res.Incoming {
|
||||
for _, edge := range edges {
|
||||
if edge == nil || idSet[edge.IssueID] {
|
||||
continue
|
||||
}
|
||||
if bySource[target] == nil {
|
||||
bySource[target] = make(map[string]bool)
|
||||
}
|
||||
bySource[target][edge.IssueID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
out := make(map[string][]string, len(bySource))
|
||||
for target, dependents := range bySource {
|
||||
out[target] = workapi.SortedDeleteIDs(dependents)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
88
internal/storage/uow/deleter_contract_test.go
Normal file
88
internal/storage/uow/deleter_contract_test.go
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
package uow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/backend/conformance"
|
||||
)
|
||||
|
||||
// TestDeleterContract runs the Deleter contract against the unit-of-work
|
||||
// provider — the one implementation that does not run
|
||||
// internal/storage/issueops.DeleteInTx, and the one that reaches the same
|
||||
// questions through the domain use cases. It is the SECOND of two votes, not
|
||||
// the third: the two store backends share the other body.
|
||||
//
|
||||
// It is also the backend this role changes most. Before this commit the proxied
|
||||
// route hardcoded cascade at both of its call sites and REFUSED `--cascade` as
|
||||
// an unsupported flag, so there was no way to delete an issue on a team server
|
||||
// without taking its dependents — the guard and the orphan mode below are new
|
||||
// behaviour here rather than a re-assertion of old.
|
||||
//
|
||||
// One provider for the whole suite (each newUOWRoleFixtureProvider boots a real
|
||||
// Dolt sql-server) and NO t.Parallel: this backend has no per-test
|
||||
// copy-on-write branch, so dolt_log and the issues table are database-global.
|
||||
func TestDeleterContract(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
fixture := newUOWDeleterFixture(t, ctx, "del")
|
||||
|
||||
t.Run("RefusesAMalformedRequest", func(t *testing.T) {
|
||||
conformance.RunDeleterRefusesAMalformedRequest(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RefusesAnAbsentID", func(t *testing.T) {
|
||||
conformance.RunDeleterRefusesAnAbsentID(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RefusesDependentsOutsideTheRequest", func(t *testing.T) {
|
||||
conformance.RunDeleterRefusesDependentsOutsideTheRequest(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ForceOrphansDependents", func(t *testing.T) {
|
||||
conformance.RunDeleterForceOrphansDependents(t, ctx, fixture)
|
||||
})
|
||||
t.Run("CascadeDeletesTheClosure", func(t *testing.T) {
|
||||
conformance.RunDeleterCascadeDeletesTheClosure(t, ctx, fixture)
|
||||
})
|
||||
t.Run("ErasesAcrossBothPlanes", func(t *testing.T) {
|
||||
conformance.RunDeleterErasesAcrossBothPlanes(t, ctx, fixture)
|
||||
})
|
||||
t.Run("CollapsesDuplicateIDs", func(t *testing.T) {
|
||||
conformance.RunDeleterCollapsesDuplicateIDs(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RewritesReferencesInNeighbors", func(t *testing.T) {
|
||||
conformance.RunDeleterRewritesReferencesInNeighbors(t, ctx, fixture)
|
||||
})
|
||||
t.Run("DryRunChangesNothing", func(t *testing.T) {
|
||||
conformance.RunDeleterDryRunChangesNothing(t, ctx, fixture)
|
||||
})
|
||||
t.Run("RecordsAtMostOneHistoryEntry", func(t *testing.T) {
|
||||
conformance.RunDeleterRecordsAtMostOneHistoryEntry(t, ctx, fixture)
|
||||
})
|
||||
t.Run("DoesNotMutateTheCallerRequest", func(t *testing.T) {
|
||||
conformance.RunDeleterDoesNotMutateTheCallerRequest(t, ctx, fixture)
|
||||
})
|
||||
}
|
||||
|
||||
func newUOWDeleterFixture(t *testing.T, ctx context.Context, prefix string) conformance.DeleterFixture {
|
||||
t.Helper()
|
||||
provider := newUOWRoleFixtureProvider(t, ctx, prefix)
|
||||
// Through the capability accessor, not NewDeleter: a provider that stopped
|
||||
// offering the role is the regression, and a constructor call would hide
|
||||
// it.
|
||||
source, ok := provider.(DeleterSource)
|
||||
if !ok {
|
||||
t.Fatalf("provider %T does not offer the Deleter accessor", provider)
|
||||
}
|
||||
deleter, err := source.Deleter()
|
||||
if err != nil {
|
||||
t.Fatalf("Deleter(): %v", err)
|
||||
}
|
||||
kit := newUOWRoleFixtureKit(provider, prefix)
|
||||
return conformance.DeleterFixture{
|
||||
IssuePrefix: kit.IssuePrefix,
|
||||
Deleter: deleter,
|
||||
CreateIssue: kit.CreateIssue,
|
||||
CreateWisp: kit.CreateWisp,
|
||||
AddDependency: kit.AddDependency,
|
||||
QueryScalar: kit.QueryScalar,
|
||||
CountHistory: kit.CountHistory,
|
||||
}
|
||||
}
|
||||
38
internal/telemetry/deleter.go
Normal file
38
internal/telemetry/deleter.go
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// Deleter returns the inner store's named-row erasure surface wrapped in this
|
||||
// layer's instrumentation. It recurses instead of delegating: a blind
|
||||
// delegation would return the inner deleter unspanned and untimed, and on a
|
||||
// destructive operation the span is what tells an operator which request erased
|
||||
// what and how long it held the write transaction.
|
||||
func (s *InstrumentedStorage) Deleter() (issueops.Deleter, error) {
|
||||
inner, err := s.Unwrap().Deleter()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.WrapDeleter(inner), nil
|
||||
}
|
||||
|
||||
// WrapDeleter instruments named-row erasure with this storage layer's existing
|
||||
// telemetry meter and tracer.
|
||||
func (s *InstrumentedStorage) WrapDeleter(inner issueops.Deleter) issueops.Deleter {
|
||||
return &instrumentedDeleter{storage: s, inner: inner}
|
||||
}
|
||||
|
||||
type instrumentedDeleter struct {
|
||||
storage *InstrumentedStorage
|
||||
inner issueops.Deleter
|
||||
}
|
||||
|
||||
func (c *instrumentedDeleter) Delete(ctx context.Context, request issueops.DeleteRequest) (result issueops.DeleteResult, err error) {
|
||||
ctx, span, started := c.storage.op(ctx, "Deleter.Delete")
|
||||
result, err = c.inner.Delete(ctx, request)
|
||||
c.storage.done(ctx, span, started, err)
|
||||
return result, err
|
||||
}
|
||||
|
|
@ -30,6 +30,7 @@ var roleAccessorNames = []string{
|
|||
"ReadyCounter",
|
||||
"Querier",
|
||||
"Sweeper",
|
||||
"Deleter",
|
||||
"Commenter",
|
||||
"ReadyClaimer",
|
||||
"BatchCloser",
|
||||
|
|
@ -99,6 +100,9 @@ func (s *roleAccessorStore) Querier() (issueops.Querier, error) { return s.surfa
|
|||
func (s *roleAccessorStore) Sweeper() (issueops.Sweeper, error) {
|
||||
return s.surface, s.err
|
||||
}
|
||||
func (s *roleAccessorStore) Deleter() (issueops.Deleter, error) {
|
||||
return s.surface, s.err
|
||||
}
|
||||
func (s *roleAccessorStore) ReadyClaimer() (issueops.ReadyClaimer, error) {
|
||||
return s.surface, s.err
|
||||
}
|
||||
|
|
@ -187,6 +191,10 @@ func (*roleAccessorSentinel) Query(context.Context, issueops.QueryRequest) (issu
|
|||
return issueops.IssuePage{}, nil
|
||||
}
|
||||
|
||||
func (*roleAccessorSentinel) Delete(context.Context, issueops.DeleteRequest) (issueops.DeleteResult, error) {
|
||||
return issueops.DeleteResult{}, nil
|
||||
}
|
||||
|
||||
func (*roleAccessorSentinel) Sweep(context.Context, issueops.SweepRequest) (issueops.SweepResult, error) {
|
||||
return issueops.SweepResult{}, nil
|
||||
}
|
||||
|
|
@ -244,6 +252,7 @@ func TestInstrumentedStorageInstrumentsEveryRoleAccessor(t *testing.T) {
|
|||
{"ReadyCounter", func() (any, error) { return wrapped.ReadyCounter() }},
|
||||
{"Querier", func() (any, error) { return wrapped.Querier() }},
|
||||
{"Sweeper", func() (any, error) { return wrapped.Sweeper() }},
|
||||
{"Deleter", func() (any, error) { return wrapped.Deleter() }},
|
||||
{"Commenter", func() (any, error) { return wrapped.Commenter() }},
|
||||
{"ReadyClaimer", func() (any, error) { return wrapped.ReadyClaimer() }},
|
||||
{"BatchCloser", func() (any, error) { return wrapped.BatchCloser() }},
|
||||
|
|
@ -290,6 +299,7 @@ func TestInstrumentedStorageRoleAccessorsPropagateInnerErrors(t *testing.T) {
|
|||
{"ReadyCounter", func() (any, error) { return wrapped.ReadyCounter() }},
|
||||
{"Querier", func() (any, error) { return wrapped.Querier() }},
|
||||
{"Sweeper", func() (any, error) { return wrapped.Sweeper() }},
|
||||
{"Deleter", func() (any, error) { return wrapped.Deleter() }},
|
||||
{"Commenter", func() (any, error) { return wrapped.Commenter() }},
|
||||
{"ReadyClaimer", func() (any, error) { return wrapped.ReadyClaimer() }},
|
||||
{"BatchCloser", func() (any, error) { return wrapped.BatchCloser() }},
|
||||
|
|
|
|||
82
internal/workapi/delete.go
Normal file
82
internal/workapi/delete.go
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
package workapi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// The shared, DATABASE-FREE half of issueops.Deleter: what a delete request
|
||||
// means before anything is read, and how the two answers that name rows —
|
||||
// the orphan list and the dependents refusal — are ordered.
|
||||
//
|
||||
// Every implementation runs these, so `bd delete` has one definition of a
|
||||
// malformed request rather than one per backend, and the parts that decide
|
||||
// what the answer MEANS are pinned in delete_test.go without a database.
|
||||
//
|
||||
// What is NOT here is the deletion. The existence probe, the guard and the
|
||||
// erasure need one transaction (issueops.Deleter.Delete), which no interface
|
||||
// above a store publishes; the bodies live in
|
||||
// internal/storage/issueops/delete.go and in the unit-of-work provider.
|
||||
|
||||
// ValidateDeleteRequest applies the request rules every Deleter implementation
|
||||
// shares, before anything is read.
|
||||
//
|
||||
// There is deliberately no require-a-filter analog of the sweep gate here.
|
||||
// A delete request carries no predicate at all: a caller cannot spell
|
||||
// "everything" without typing every id, so the shape that gate protects
|
||||
// against does not exist on this role. The guard that does matter — dependents
|
||||
// outside the request — needs the graph and therefore lives in the bodies.
|
||||
func ValidateDeleteRequest(in issueops.DeleteRequest) error {
|
||||
if len(in.IDs) == 0 {
|
||||
return fmt.Errorf("%w: delete requires at least one issue id", issueops.ErrValidation)
|
||||
}
|
||||
for i, id := range in.IDs {
|
||||
if strings.TrimSpace(id) == "" {
|
||||
return fmt.Errorf("%w: delete id at position %d is blank", issueops.ErrValidation, i)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// NormalizeDeleteIDs collapses duplicates, keeping the caller's FIRST mention
|
||||
// of each id, and trims surrounding whitespace.
|
||||
//
|
||||
// First-mention order rather than sorted, because it is the order the front
|
||||
// doors echo back in their "issues not found" line and in the confirmation
|
||||
// hint they print, and a caller re-reading its own `--from-file` list against
|
||||
// that output should not have to re-sort it.
|
||||
//
|
||||
// It assumes a request already accepted by ValidateDeleteRequest, so no entry
|
||||
// trims to empty.
|
||||
func NormalizeDeleteIDs(ids []string) []string {
|
||||
seen := make(map[string]bool, len(ids))
|
||||
out := make([]string, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
trimmed := strings.TrimSpace(id)
|
||||
if seen[trimmed] {
|
||||
continue
|
||||
}
|
||||
seen[trimmed] = true
|
||||
out = append(out, trimmed)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// SortedDeleteIDs copies and sorts a set of ids ascending. It is what puts
|
||||
// DeleteResult.Orphaned and DependentsOutsideRequestError.Dependents in the
|
||||
// order issueops.DeleteResult promises, from bodies that collect them out of
|
||||
// maps and would otherwise publish Go's map order.
|
||||
func SortedDeleteIDs(ids map[string]bool) []string {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make([]string, 0, len(ids))
|
||||
for id := range ids {
|
||||
out = append(out, id)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
99
internal/workapi/delete_test.go
Normal file
99
internal/workapi/delete_test.go
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
package workapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/steveyegge/beads/issueops"
|
||||
)
|
||||
|
||||
// The database-free half of issueops.Deleter, pinned in milliseconds. Every
|
||||
// backend runs these functions, so a disagreement about what a malformed
|
||||
// request means, or about what order the ids come back in, is caught here
|
||||
// rather than three times over in the conformance suite.
|
||||
|
||||
func TestValidateDeleteRequest(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
request issueops.DeleteRequest
|
||||
wantErr bool
|
||||
}{
|
||||
{"one id", issueops.DeleteRequest{IDs: []string{"bd-1"}}, false},
|
||||
{"several ids", issueops.DeleteRequest{IDs: []string{"bd-1", "bd-2"}}, false},
|
||||
{"untrimmed id is accepted and normalized later", issueops.DeleteRequest{IDs: []string{" bd-1 "}}, false},
|
||||
{"nil ids", issueops.DeleteRequest{}, true},
|
||||
{"empty ids", issueops.DeleteRequest{IDs: []string{}}, true},
|
||||
{"blank id", issueops.DeleteRequest{IDs: []string{""}}, true},
|
||||
{"whitespace id", issueops.DeleteRequest{IDs: []string{"\t "}}, true},
|
||||
{"blank beside a real one", issueops.DeleteRequest{IDs: []string{"bd-1", " "}}, true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
err := ValidateDeleteRequest(test.request)
|
||||
if test.wantErr {
|
||||
if !errors.Is(err, issueops.ErrValidation) {
|
||||
t.Fatalf("error = %v, want ErrValidation", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("error = %v, want nil", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeDeleteIDs pins FIRST-MENTION order rather than sorted order. It
|
||||
// is the order both front doors echo back — in "issues not found" and in the
|
||||
// `--force` hint they print — so a caller re-reading its own `--from-file` list
|
||||
// against that output should not have to re-sort it.
|
||||
func TestNormalizeDeleteIDs(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
in []string
|
||||
want []string
|
||||
}{
|
||||
{"unchanged", []string{"bd-1", "bd-2"}, []string{"bd-1", "bd-2"}},
|
||||
{"duplicates collapse to the first mention", []string{"bd-2", "bd-1", "bd-2"}, []string{"bd-2", "bd-1"}},
|
||||
{"whitespace is trimmed before comparing", []string{" bd-1", "bd-1 "}, []string{"bd-1"}},
|
||||
{"order is not sorted", []string{"bd-z", "bd-a"}, []string{"bd-z", "bd-a"}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if got := NormalizeDeleteIDs(test.in); !reflect.DeepEqual(got, test.want) {
|
||||
t.Errorf("NormalizeDeleteIDs(%v) = %v, want %v", test.in, got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeDeleteIDsDoesNotMutateTheCaller is the pin behind
|
||||
// issueops.DeleteRequest's "IDs is read, never written through": normalizing in
|
||||
// place is the most natural way to write this function and would hand the
|
||||
// caller back a shorter, reordered version of its own slice.
|
||||
func TestNormalizeDeleteIDsDoesNotMutateTheCaller(t *testing.T) {
|
||||
in := []string{" bd-2 ", "bd-1", "bd-2"}
|
||||
snapshot := append([]string(nil), in...)
|
||||
|
||||
NormalizeDeleteIDs(in)
|
||||
|
||||
if !reflect.DeepEqual(in, snapshot) {
|
||||
t.Errorf("caller's slice changed: got %v, want %v", in, snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSortedDeleteIDs pins the ascending order DeleteResult.Orphaned and
|
||||
// DependentsOutsideRequestError.Dependents promise. Both are collected out of
|
||||
// maps, so without this they would publish Go's map order and a caller
|
||||
// diffing two runs would see spurious changes.
|
||||
func TestSortedDeleteIDs(t *testing.T) {
|
||||
if got := SortedDeleteIDs(nil); got != nil {
|
||||
t.Errorf("SortedDeleteIDs(nil) = %v, want nil", got)
|
||||
}
|
||||
if got := SortedDeleteIDs(map[string]bool{}); got != nil {
|
||||
t.Errorf("SortedDeleteIDs(empty) = %v, want nil", got)
|
||||
}
|
||||
got := SortedDeleteIDs(map[string]bool{"bd-c": true, "bd-a": true, "bd-b": true})
|
||||
if want := []string{"bd-a", "bd-b", "bd-c"}; !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("SortedDeleteIDs() = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
|
@ -518,3 +518,35 @@ func TestSweeperExposesTypedUnsupportedError(t *testing.T) {
|
|||
t.Fatalf("Sweeper() error = %v, want *beads.ErrUnsupported", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleterKeepsTelemetryOutermost is the named-row erasure role's version of
|
||||
// the same pin, and the SECOND write role to answer the way the reads do: there
|
||||
// is no on_delete hook to fire (internal/storage/hook_deleter.go), so the hook
|
||||
// decorator adds no layer and the outermost surface a caller gets is the
|
||||
// instrumented one.
|
||||
func TestDeleterKeepsTelemetryOutermost(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")
|
||||
}
|
||||
|
||||
deleter, err := storage.NewHookFiringStore(instrumented, nil).Deleter()
|
||||
if err != nil {
|
||||
t.Fatalf("Deleter() error = %v", err)
|
||||
}
|
||||
if got := reflect.TypeOf(deleter).String(); got != "*telemetry.instrumentedDeleter" {
|
||||
t.Fatalf("outer layer = %s, want the telemetry wrapper unwrapped by the hook decorator", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleterExposesTypedUnsupportedError(t *testing.T) {
|
||||
deleter, err := (*dolt.DoltStore)(nil).Deleter()
|
||||
if deleter != nil {
|
||||
t.Fatalf("Deleter() deleter = %T, want nil", deleter)
|
||||
}
|
||||
var unsupported *beads.ErrUnsupported
|
||||
if !errors.As(err, &unsupported) {
|
||||
t.Fatalf("Deleter() error = %v, want *beads.ErrUnsupported", err)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
268
issueops/deleter.go
Normal file
268
issueops/deleter.go
Normal file
|
|
@ -0,0 +1,268 @@
|
|||
package issueops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// DeleteRequest names the rows to erase and says what to do about the rows
|
||||
// that point at them.
|
||||
//
|
||||
// IT IS NOT A SELECTION. Sweeper describes a SET and lets the implementation
|
||||
// resolve it; this one is handed ids and deletes those. That difference is why
|
||||
// this request carries no predicate at all — no status, no cutoff, no glob —
|
||||
// and why it needs no require-a-filter gate: a caller cannot spell "everything"
|
||||
// here without typing every id.
|
||||
//
|
||||
// Implementations never mutate caller-owned request values: IDs is read, never
|
||||
// written through, and never sorted in place.
|
||||
type DeleteRequest struct {
|
||||
// Actor attributes the deletion wherever the backend records attribution.
|
||||
// It is not an authorization boundary, and an empty Actor is accepted for
|
||||
// the reason SweepRequest.Actor is: the deletion of a row leaves no row to
|
||||
// attribute it on. It DOES reach the rewritten neighbors, which survive,
|
||||
// so a workspace that cares who rewrote a description passes one.
|
||||
Actor string
|
||||
// IDs names the rows to delete, in either plane. It is REQUIRED: an empty
|
||||
// or all-blank slice is ErrValidation rather than a no-op, because "delete
|
||||
// nothing" is never what a caller meant to ask and a silent zero is how a
|
||||
// broken id list looks from the outside.
|
||||
//
|
||||
// DUPLICATES COLLAPSE and the surviving order is the caller's first
|
||||
// mention of each id. An id repeated in a `--from-file` list is one row,
|
||||
// not a row deleted twice.
|
||||
//
|
||||
// EVERY ID MUST NAME A STORED ROW. An id that names none is ErrNotFound
|
||||
// and NOTHING IS DELETED — not even the ids beside it that did resolve.
|
||||
// That is the all-or-nothing this operation needs most: a batch that
|
||||
// deleted eight of ten and then reported a typo has already done the part
|
||||
// that cannot be undone.
|
||||
//
|
||||
// IDs ARE EXACT. Prefix resolution, cross-repository routing and `bd`'s
|
||||
// other id conveniences happen at the front door, above this role, because
|
||||
// resolving an ambiguous prefix to a row and then deleting it is the one
|
||||
// place a convenience is not one.
|
||||
IDs []string
|
||||
// Cascade also deletes the TRANSITIVE CLOSURE of everything that depends
|
||||
// on the named rows, in both planes. It is what `bd delete --cascade`
|
||||
// asks for.
|
||||
//
|
||||
// WITH CASCADE THERE IS NOTHING LEFT TO ORPHAN, by construction: the
|
||||
// closure contains every dependent of every row it deletes. So Cascade
|
||||
// makes Force moot rather than conflicting with it — a request carrying
|
||||
// both is legal and behaves as Cascade, and DeleteResult.Orphaned comes
|
||||
// back empty.
|
||||
//
|
||||
// The traversal is BOUNDED. A closure that grows past the backend's
|
||||
// runaway limit aborts the whole request and deletes nothing rather than
|
||||
// deleting as far as it got.
|
||||
Cascade bool
|
||||
// Force deletes the named rows and leaves rows that depended on them
|
||||
// ORPHANED — their edges into the deleted rows go, they themselves stay,
|
||||
// and DeleteResult.Orphaned names them.
|
||||
//
|
||||
// WITHOUT Cascade AND WITHOUT Force, a named row that some row OUTSIDE the
|
||||
// request depends on is refused: the request fails with a
|
||||
// DependentsOutsideRequestError and nothing is deleted. That guard is the
|
||||
// role's, not a front door's, for the reason Sweeper's require-a-filter
|
||||
// gate is: a second front door that inherited the capability without the
|
||||
// guard would orphan a workspace's graph by omission.
|
||||
//
|
||||
// A dependent INSIDE the request is not a dependent for this purpose — a
|
||||
// batch that names both ends of an edge is deleting the edge too, and
|
||||
// refusing it would make `bd delete a b` fail on exactly the pair a caller
|
||||
// took care to list together.
|
||||
Force bool
|
||||
// DryRun reports what the deletion WOULD do and changes nothing, including
|
||||
// history.
|
||||
//
|
||||
// IT REFUSES WHERE THE REAL RUN WOULD REFUSE, and that is the whole value
|
||||
// of it on this operation: an unforced preview over a row with outside
|
||||
// dependents fails with the same DependentsOutsideRequestError, and a
|
||||
// preview naming an absent id fails with the same ErrNotFound, so a caller
|
||||
// that got a clean preview has learned the real run will not stop
|
||||
// half-explained. It is computed against the same snapshot the real
|
||||
// deletion would have used.
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// DeleteResult reports one deletion.
|
||||
//
|
||||
// EVERY NUMBER DESCRIBES THE SAME SNAPSHOT, because the guard, the cascade
|
||||
// expansion, the deletion and the reference rewrite all run in ONE
|
||||
// transaction. See Deleter.Delete.
|
||||
type DeleteResult struct {
|
||||
// DryRun echoes the request, so a result value carries whether its numbers
|
||||
// describe rows that are gone or rows that would go without the caller
|
||||
// having to keep the request beside it.
|
||||
DryRun bool
|
||||
// Deleted is how many rows were deleted, or — under DryRun — would be.
|
||||
// Under Cascade it counts the whole closure, so it is normally larger than
|
||||
// len(IDs) and is the number a caller should show rather than the request
|
||||
// length.
|
||||
Deleted int
|
||||
// Dependencies, Labels and Events count the ROWS OF ASSOCIATED DATA that
|
||||
// went with them: edges touching a deleted row in either direction, its
|
||||
// labels, and its recorded events. A deletion's visible effect is much
|
||||
// larger than its row count, and these are the numbers that explain it.
|
||||
Dependencies int
|
||||
Labels int
|
||||
Events int
|
||||
// ReferencesUpdated counts the SURVIVING rows whose text was rewritten —
|
||||
// rows, not occurrences: a neighbor citing two deleted ids in three
|
||||
// fields counts once. It is 0 under DryRun, because a preview rewrites
|
||||
// nothing and reporting a number there would describe an edit that did not
|
||||
// happen.
|
||||
ReferencesUpdated int
|
||||
// Orphaned names the surviving rows that depended on something this
|
||||
// request deleted, in ascending id order.
|
||||
//
|
||||
// It is populated exactly when the request carried Force without Cascade —
|
||||
// the only mode in which orphaning is possible — and is empty otherwise.
|
||||
// It is also carried on the DependentsOutsideRequestError the unforced
|
||||
// mode returns, so the same fact reaches a caller whichever answer it got.
|
||||
//
|
||||
// It is DIRECT dependents only. A row two edges away loses no edge and is
|
||||
// not orphaned by this deletion; it is merely blocked by something that is
|
||||
// now blocked by nothing.
|
||||
Orphaned []string
|
||||
}
|
||||
|
||||
// ErrDependentsOutsideRequest classifies the unforced refusal: a named row has
|
||||
// a dependent the request did not name, and neither Cascade nor Force said
|
||||
// what to do about it.
|
||||
//
|
||||
// It lives beside the role rather than in errors.go because it is meaningless
|
||||
// without DeleteRequest.Cascade and DeleteRequest.Force to explain it, and
|
||||
// errors.go is the file every parallel role slice touches.
|
||||
var ErrDependentsOutsideRequest = errors.New("dependents outside deletion set")
|
||||
|
||||
// DependentsOutsideRequestError reports WHICH row was blocked and by WHAT, so
|
||||
// a caller can name them without parsing the message. It wraps the sentinel
|
||||
// rather than replacing it.
|
||||
//
|
||||
// It names ONE blocked row — the first the implementation reached — rather
|
||||
// than every blocked row in the request. That is deliberate and matches the
|
||||
// only answer a caller can act on: the request is refused whole, so the second
|
||||
// blocked row changes nothing about what to do next, and enumerating all of
|
||||
// them would cost a full scan on the path that deletes nothing.
|
||||
type DependentsOutsideRequestError struct {
|
||||
// IssueID is the named row that has dependents outside the request.
|
||||
IssueID string
|
||||
// Dependents are that row's direct dependents that the request did not
|
||||
// name, in ascending id order.
|
||||
Dependents []string
|
||||
}
|
||||
|
||||
func (e *DependentsOutsideRequestError) Error() string {
|
||||
return fmt.Sprintf("issue %s has dependents not in deletion set; use --cascade to delete them or --force to orphan them", e.IssueID)
|
||||
}
|
||||
|
||||
// Unwrap makes DependentsOutsideRequestError match ErrDependentsOutsideRequest.
|
||||
func (e *DependentsOutsideRequestError) Unwrap() error { return ErrDependentsOutsideRequest }
|
||||
|
||||
// NotFoundError reports which of a request's ids named no stored row. It wraps
|
||||
// ErrNotFound, so a caller that only wants to classify the failure still can.
|
||||
//
|
||||
// It names EVERY missing id rather than the first, unlike the dependents
|
||||
// refusal above, because this one is a typo report: a caller handed a list and
|
||||
// wants the whole list of what did not resolve, and the ids are already in
|
||||
// hand from the probe that found them missing.
|
||||
type NotFoundError struct {
|
||||
// IDs are the requested ids that named no row in either plane, in the
|
||||
// order the request spelled them.
|
||||
IDs []string
|
||||
}
|
||||
|
||||
func (e *NotFoundError) Error() string {
|
||||
return "issues not found: " + strings.Join(e.IDs, ", ")
|
||||
}
|
||||
|
||||
// Unwrap makes NotFoundError match ErrNotFound.
|
||||
func (e *NotFoundError) Unwrap() error { return ErrNotFound }
|
||||
|
||||
// Deleter describes erasure of NAMED rows — the capability behind
|
||||
// `bd delete` — and, like every other capability here, 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 A DIFFERENT QUESTION FROM ITS NEIGHBORS.
|
||||
//
|
||||
// - Sweeper erases a SET the caller described: closed rows of one tier,
|
||||
// narrowed by a cutoff and a glob. This erases rows the caller NAMED. The
|
||||
// difference decides where the safety lives — a description can be
|
||||
// accidentally too wide, so Sweeper carries a require-a-filter gate; a
|
||||
// list of ids cannot, so this one's guard is about the graph instead.
|
||||
// - Lifecycle closes ONE issue and leaves the row. A closed row is still
|
||||
// readable, still cited, still in a report. This one leaves nothing, which
|
||||
// is why its unforced mode refuses rather than warns.
|
||||
// - DependencyEditor removes EDGES. This removes edges as a consequence of
|
||||
// removing their endpoints, and the two must not be composed by a caller
|
||||
// to imitate it: unlink-then-delete is two transactions, and the window
|
||||
// between them is a graph that has already lost its edges and still has
|
||||
// the row.
|
||||
//
|
||||
// WRITES, AND THE SECOND DESTRUCTIVE ROLE IN THIS PACKAGE. Nothing it deletes
|
||||
// comes back. Its completion fires no hook, for the reason Sweeper's does not:
|
||||
// internal/hooks publishes on_create, on_update and on_close and none of them
|
||||
// names a deletion.
|
||||
//
|
||||
// Deterministic request-validation failures match ErrValidation. Result values
|
||||
// are unspecified when error is non-nil.
|
||||
type Deleter interface {
|
||||
// Delete erases req.IDs and, under Cascade, everything that depends on
|
||||
// them, and reports what it did.
|
||||
//
|
||||
// IT IS ONE TRANSACTION, and on this role that covers one thing it did not
|
||||
// cover before: THE TEXT-REFERENCE REWRITE. The direct CLI route deleted
|
||||
// the rows in a transaction and then rewrote the neighbors' text in
|
||||
// separate statements afterwards, so a failure between the two left a
|
||||
// workspace whose rows were gone and whose descriptions still pointed at
|
||||
// them by id. Here the existence probe, the guard, the cascade expansion,
|
||||
// the deletion and the rewrite all see one snapshot and land or fail
|
||||
// together.
|
||||
//
|
||||
// WHAT THAT COSTS, said out loud because it is a real trade: the
|
||||
// transaction is now as large as the deletion PLUS its neighborhood. A
|
||||
// request whose neighbors are numerous enough to exceed a backend's write
|
||||
// timeout fails whole and deletes nothing, where the split version would
|
||||
// have deleted the rows and left the text stale. That is the better of the
|
||||
// two failures, but it is a ceiling: a caller deleting a very large set
|
||||
// splits the request rather than expecting progress.
|
||||
//
|
||||
// WHICH ROWS GET REWRITTEN is the deletion set's GRAPH NEIGHBORS — the
|
||||
// surviving rows joined to a deleted row by a dependency edge in either
|
||||
// direction — and not the workspace. Each occurrence of a deleted id in a
|
||||
// neighbor's description, notes, design or acceptance criteria becomes
|
||||
// `[deleted:<id>]`, matched at ASCII word boundaries the way
|
||||
// SweepRequest.ProtectReferenced matches: `be-1` rewrites in "see (be-1)."
|
||||
// and not inside `xbe-1` or `be-12`. A row that cites a deleted id in
|
||||
// prose WITHOUT an edge to it is left alone, because a workspace-wide text
|
||||
// scan on every delete is a cost this operation does not take.
|
||||
//
|
||||
// THE ORDER THE REFUSALS HAPPEN IN IS PART OF THE ANSWER, because a
|
||||
// request can fail two ways at once: request validation, then the
|
||||
// existence probe, then the dependents guard. `bd delete typo real-with-
|
||||
// dependents` reports the TYPO, which is the one the caller can fix
|
||||
// without deciding anything.
|
||||
//
|
||||
// REFUSALS:
|
||||
//
|
||||
// - an empty or all-blank IDs, and an IDs containing a blank entry:
|
||||
// ErrValidation, before anything is read;
|
||||
// - an id naming no row in either plane: *NotFoundError, matching
|
||||
// ErrNotFound;
|
||||
// - without Cascade and without Force, a named row with a dependent the
|
||||
// request did not name: *DependentsOutsideRequestError, matching
|
||||
// ErrDependentsOutsideRequest.
|
||||
//
|
||||
// EVERY ONE OF THEM DELETES NOTHING, under DryRun and otherwise.
|
||||
//
|
||||
// A DRY RUN CHANGES NOTHING, including history: an implementation that
|
||||
// records a version-control entry for a deletion records none for a dry
|
||||
// run. Where an implementation versions at all, one call records AT MOST
|
||||
// ONE entry — a deletion is one act, not one per row.
|
||||
Delete(ctx context.Context, req DeleteRequest) (DeleteResult, error)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue