* feat(http): serve list/show counts/dep tree/ping, close+reopen under a session, one-lookup not-found (S6b/S6c/S6d) S6c. The external-dependency decorator rebuilt its role views from the legacy DoltStorage seam (storereader over itself, IsBlocked, GetDependencyTree, ClaimReadyIssue), which a remote store only partly serves: `bd list`/`bd children` refused on the SearchIssuesWithCounts stub, `bd show --json` printed zero counts, the default `bd dep tree` refused, `bd ready --claim` and `bd close` of an externally blocked issue reached unsupported paths. For a storage.RemoteBackendStore each view now passes the inner role through and lays the policy over it in role terms (externaldeps/remote_roles.go): ready reads and the ready claim exclude the workspace-wide blocked set over a widened window; per-issue checks (claim, close, batch close, list annotations, tree leaves) read only the named issues' edges through EdgeReader instead of every edge in the workspace. A server advertising policy.external_dependencies (MC's does) gets a plain passthrough. `bd ping` uses a new storage.Pinger, which the http store answers with its authenticated context read. S6d. A store reporting storage.CallerAttributionLimitedStore (http) cannot carry a Provenance label or a patch's closed_by_session. The library still refuses both; the CLI omits them where nothing is lost: `bd reopen`'s fixed "bd: reopen <id>" label (the server labels the same entry), and the closed_by_session of `bd update -s closed` (attribution only, usually the ambient CLAUDE_SESSION_ID; an explicit --session prints a notice; `bd close` still records it). See cmd/bd/remote_backend.go. S6b. utils.ExactIDLookupStore: the resolver stops at exact lookups for a store with no substring search, so a missing prefixed id is a not-found (beadserrors.ErrNotFound, "no issue found matching") after one getIssue. The general resolver no longer repeats an identical normalized probe. The http SearchIssueIDs answers D11's partial-id refusal, which now unwraps to ErrNotFound. Contributor auto-routing for a remote workspace reads local config only, so the not-found fallback pays no settings round trip. `bd update <absent> --claim` (gc's hook claim) answers a gc-classifiable not-found in at most two requests. Served e2e (backend/http/e2e_remote_roles_test.go): every gc list shape and `bd children` against embedded, `show --json` count parity, default dep tree parity, external blocking still enforced, close/reopen under CLAUDE_SESSION_ID, missing-id request counts, absent-id claim against the current server and the MC handshake mask, policy passthrough under the MC mask, ping. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(externaldeps): role-level remote reader and claimer cases bd ready and bd update --claim reach the policy through the legacy seam and the lifecycle guard, so the remote Reader.Ready exclusion and the remote Claimer guard (what bd serve and library callers reach) are pinned at the role level with a fake remote store. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * feat(http): bd serve advertises policy.external_dependencies; clients pass through bd serve composes every ready, claim, claim-next, close, blocking and tree role through the external-dependency policy, but never said so. Every client therefore ran the policy a second time, with the CLIENT machine's external-project config, and claim-next became a non-atomic read-then-claim loop on the client. The server now advertises the token exactly when the roles it serves were composed through the policy: httpapi.Config.ExternalDependencyPolicy, which bd serve derives from its actual chain (externaldeps.Applied for the store arm, externaldeps.AppliedToProvider for the provider arm). A server handed raw roles still withholds it, so the token stays truthful. Against a server that advertises it, every remote role view hands the request to the server's own role untouched: no client validation, no edge reads, claim-next is the server's one atomic call, and the ready count is the server's countReadyWork (new remoteReadyCounter). The client-side policy remains only for servers that do not advertise the token. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(create): default created_by to the request's actor in the create role created_by was stamped in two front doors and never in the library: the CLI (creationActorStamp, with a remote-workspace special case) and the three httpapi create handlers. A library caller of Lifecycle.Create or BatchCreator with an empty CreatedBy stored "" locally and the actor over http. PreparePublicCreateRequest, which every create shape prepares through (Lifecycle.Create, BatchCreator items, batch-apply create items), now defaults an empty CreatedBy to request.Actor; an explicit value is kept. The handlers no longer stamp, `bd create` and the state event create pass only the actor, and creationActorStamp/isRemoteBackendWorkspace are gone. The CLI sites that still create through the raw CreateIssue seam (swarm, todo, gate, the create form) keep stamping currentActor(): that seam is shared with import, where defaulting would re-attribute imported rows, and the http store refuses it anyway, so the remote special case was never reachable there. Conformance: the lifecycle-create, batch-creator and batch-apply contracts now pin created_by == actor for an item that names none, on every leg. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(httpclient): GetIssue answers a miss with storage.ErrNotFound, like the local stores The http store's raw GetIssue answered a missing id with (nil, nil), where DoltStore and the embedded store return a wrapped storage.ErrNotFound. A caller written against the backend contract read the http miss as a hit: `bd create --graph` refused every explicit-id plan over http (patched in cmd/bd on feat/http-mc-corpus; that workaround is reverted there). GetIssue now returns the miss (and the empty id) as storage.ErrNotFound, spelled as issueops.GetIssueInTx spells it. GetLabels, which reads through GetIssue, keeps the local read's "no labels" answer for a missing id; the `bd list --parent` walk reads the typed miss as "parent issue not found". The served bridge test now holds the local reference store and the http store to the same miss: ErrNotFound with the same text. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(createbatchequiv): re-record the apply golden for the created_by default c2866ea7fe made the create role default an empty CreatedBy to the request's actor, so every create item of the apply scenario's batch (actor "apply-writer") now stores created_by "apply-writer" instead of "". TestCreateBatchFastPathsMatchPerRow_*/apply compared the stored rows to a digest recorded before that change and failed on exactly the three tables the column reaches: issues and wisps (the row) and events (the update event's old-value snapshot). Fast and per-row bodies still agree; the batch-apply conformance contract pins the same value. Bisected with bazel: passes at be92efe40f's integ twin 696f7acc8e, fails from the created_by commit on. Only apply.json's three digests move. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * style: gofmt ledger.go and the externaldeps remote-roles test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cmd/bd): bd create reads routing settings local-only on a remote backend too determineAutoRoutedRepoPath skipped a remote backend's settings document (routing targets are local paths that one shared document cannot name for every client), but getRoutingConfigValue, which `bd create` and migrate-personal read routing.* and contributor.* through, still asked it. The same workspace could route a create one way and a lookup another, and every create paid a settings round trip per key. Both now go through routingSettingsStore: nil for a remote backend, so routing comes from config.yaml / the environment only there, and a local store is still consulted. A unit test holds both reads to the rule with a store that counts settings reads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cmd/bd): say so when update -s closed drops an ambient CLAUDE_SESSION_ID Over http `bd update -s closed` cannot carry closed_by_session, so the CLI drops it rather than refusing the close. An explicit --session printed a notice; the ambient CLAUDE_SESSION_ID every agent under Claude Code exports was dropped without a word, a silent data difference from a local backend (the served corpus's mc-update-meta-status-closed). The drop is now named on stderr in both cases, once per command, pointing at `bd close`, whose wire operation records the session. The served e2e asserts the notice. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(backend/http): hold bd list --limit 2 to each side's own unlimited order TestE2E_ListWithGCFiltersMatchesEmbedded compared the --limit 2 rows of the served and embedded workspaces as sets. The seed has four P2 rows, so the limit cuts a priority tie whose created_at order differs between two workspaces seeded seconds apart: a test-only flake, the order itself being total. Each side's two rows must now be, in order, the first two of that same side's --limit 0 listing; the unlimited listings are still compared across sides by the shape loop. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: unit-tier pins for the created_by default, the policy token and the GetIssue miss Three review mutations were caught only by a heavier tier (the uow conformance legs, the served httpclient tier) or by one package's test alone. Each now has a unit test where its rule lives: - issueops: PreparePublicCreateRequest defaults an empty CreatedBy to the actor and keeps an explicit one, without mutating the caller's request. - externaldeps: the policy layer AppliedToProvider finds becomes the handshake's policy.external_dependencies through httpapi.Listen, the composition bd serve performs, and a raw provider's handshake lacks it. - httpclient (no embedded engine): GetIssue over the real wire client against a stub server answers a 404 not_found, and the empty id without dialing, as storage.ErrNotFound spelled like the local stores. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(changelog): S6b/c/d entries match the code The S6 entry still said `bd create` suppresses created_by on a remote workspace and that the external-dependency policy runs client-side. Since S6b/c/d, created_by defaults to the actor in the library on every backend, and every bd serve composed through the policy advertises policy.external_dependencies, so clients pass those operations through; the client-side policy (now in role terms) runs only against a server that does not advertise it. New entries: the advertised policy token, bd ping over http, the created_by library default, closed_by_session dropped by an http `bd update -s closed` (with a notice, typed or ambient), reopen without a Provenance label over http, local-only routing.* / contributor.* on a remote backend, GetIssue's miss as storage.ErrNotFound, and list/children/show counts/dep tree over http. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(externaldeps): keep S6's list --ready, --claim-next refusal and lost-race error on the S6c composition The re-adopted S6 head (#7288) carries the review fixup's remote role composition; S6c replaces it with its own (rolesAreRemote, the widened ready window, the policy passthrough). Two behaviours S6 shipped and its reviews pinned would otherwise go: - bd close --claim-next against a server that does not apply the policy is refused whole, before anything is read or closed, with "the served batch close cannot carry a next claim, so nothing was closed; close without --claim-next, then run `bd ready --claim`". S6c passed the batch to the http closer, whose W-CloseBatchRequest.ClaimNext refusal drops the remedy, so TestE2E_BDOverHTTP's two refuseClaimNext steps went red. A request invalid on every backend is still ErrValidation first, and a server that applies the policy still gets the request untouched. - remoteReadyClaimer.ClaimNext reports a page on which every candidate was lost to another actor as "claim ready: lost N races ...", not as the empty answer that means there is no work. - `bd list --ready` (List with ReadyFlag) is answered by the policy store's own reader over the served ready reads, as S6 does. S6c passed it to the served listing, which cannot carry ReadyFlag (httpclient ledger row E-ListRequest.ReadyFlag), so it exited 1 over http with or without external refs; TestE2E_BDOverHTTP and TestServedRolesKeepTheExternalDependencyPolicy were red on it. TestRemoteReaderAnswersAReadyListingWithoutTheWireFlag pins it, with the fake's served List refusing ReadyFlag as the wire does. S6's composition tests now run against S6c as remote_roles_composition_test.go. Their fake serves Ready the way a server does (the S6 composition read ready work through the legacy policy reader instead), and two call logs gain that Ready. TestRemoteBatchCloserRefusesANextClaim, TestRemoteBatchCloserValidatesANextClaimFirst and TestRemoteReadyClaimerReportsLostRaces were red on S6c before this change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(externaldeps): unassigned claim-next and fail-closed close reads Review fixes for the S6c composition against a server that does not advertise policy.external_dependencies: the two majors of review attempt 1, plus the minors on the same code. - ReadyClaimer: the composed claim-next reads only open, unassigned ready rows (Unassigned=true, Assignee cleared), the candidates the local ClaimReadyIssueInTx selects. A row another actor holds, or one already assigned to the caller, is no longer taken or counted as a lost race. Each pass reads 25 candidates past the blocked rows, as httpclient's composed claim does, and a full window lost end to end is read once more: claimed rows leave the unassigned set. Only a claim that tried candidates and won none is an error. - BatchCloser: an externally blocked item travels to the server only when its status read finds it closed or not found (liveRefusal). Any other read error is that item's outcome, so a transient or auth failure no longer forwards a refused close to a server that will not refuse it. - TreeWalker: a failed capability probe renders the external leaves over the walked tree instead of failing a walk the server already answered. appendTreeExternalReferences skips an id the tree holds, so an enforcing server's own leaves are not doubled. - remoteEdges names each anchor once and skips an empty one, which the http EdgeReader refuses with ErrValidation. The composition fakes now honor Unassigned/Assignee as workapi.BuildReadyFilter does, model a rival claim landing first and a failing GetIssue, and refuse an empty edge anchor as httpclient does. New: TestRemoteReadyClaimerTakesOnlyUnassignedWork, TestRemoteReadyClaimerWalksAContendedFront, TestRemoteBatchCloserAnswersAFailedReadWithIt, TestRemoteEdgesNamesEachAnchorOnce, and the probe-failure cases of TestRemoteTreeWalkerAddsExternalLeaves. Each is red with its fix reverted. From review attempt 2, three nearby cleanups: - TestServedRolesKeepTheExternalDependencyPolicy seeds open rows held by another actor and by the claimant ahead of the free work, then claims with and without an assignee filter. The unassigned-only claim is now pinned over a real served server, not only through the fakes: red with the pre-fixup remote_roles.go, with filter.Unassigned dropped, and (the filtered claim) with an explicit assignee honored. - The capabilities description in openapi.v0.yaml (and the regenerated types.gen.go comment) no longer calls the whole list build-level: policy.external_dependencies depends on how the server composed its roles, as the paragraph above it says. - createbatchequiv's golden note names issueops.PreparePublicCreateRequest instead of a commit id that is not on this branch. Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(backend/http): count a not_found read as reaching the remote in #7469's credential doors main's #7469 added TestExplicitCredentialIgnoresTheEnvPlaintextGrant. Its OpenWith and Open doors read bd-1 from plaintextRemote, which answers every issue read not_found, and the granted leg needs that read to return a nil error. That held while the http client answered a miss with (nil, nil). This branch's "fix(httpclient): GetIssue answers a miss with storage.ErrNotFound, like the local stores" makes the same read return storage.ErrNotFound. So on main plus this branch both doors fail at per_open_credential_test.go:392 ("with Target.AllowInsecureCredential: not found: issue bd-1") under plain go test. The merge is textually clean, so only a build of the merge shows it. The two store doors now count storage.ErrNotFound as success, since that answer came off the wire. The assertions are unchanged. The refused leg still needs the "refusing to send a credential" error and no request on the transport. The granted leg still needs exactly one request carrying "Bearer explicit-token": a granted read that never reaches the wire still fails at :408. Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1049 lines
45 KiB
Go
1049 lines
45 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"testing"
|
|
|
|
"github.com/steveyegge/beads/internal/httpapi/apigen"
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/issueops"
|
|
)
|
|
|
|
// The pins for POST /v0/beads/issues:batchApply. What is asserted here is the
|
|
// WIRE EDGE — that a four-level body reaches the role faithfully, that the
|
|
// tagged union's two halves are made to agree before the role sees them, that
|
|
// the result goes back LEAN, and that each of the role's typed refusals arrives
|
|
// as the documented code carrying the members that name the offending item.
|
|
// Everything below the wire is the role's.
|
|
|
|
const batchApplyPath = "/v0/beads/issues:batchApply"
|
|
|
|
func newApplyBatchServer(t *testing.T, applier *roleBatchApplier) *testServer {
|
|
t.Helper()
|
|
return newTestServer(t, rolesConfig(Config{BatchApplier: applier}))
|
|
}
|
|
|
|
// itemErr wraps a refusal the way the role does, so a case can drive the
|
|
// item-naming members without reaching into a backend.
|
|
func itemErr(index int, kind issueops.ItemKind, key, issueID string, err error) error {
|
|
return &issueops.ItemError{Index: index, Kind: kind, Key: key, IssueID: issueID, Err: err}
|
|
}
|
|
|
|
// TestApplyBatchPathReachesItsHandler: a literal collection-level custom method
|
|
// registered beside the claim's `/v0/beads/issues/{idop}` wildcard. A 404 here
|
|
// would mean the segment was parsed as a claim of an issue called ":batchApply".
|
|
func TestApplyBatchPathReachesItsHandler(t *testing.T) {
|
|
applier := &roleBatchApplier{result: issueops.ApplyBatchResult{
|
|
Items: []issueops.ItemResult{{Kind: issueops.ItemCreate, IssueID: "bd-1", Changed: true}},
|
|
}}
|
|
ts := newApplyBatchServer(t, applier)
|
|
|
|
resp := ts.claim(t, batchApplyPath, `{"actor":"alice","items":[{"kind":"create","create":{"title":"one"}}]}`)
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
|
}
|
|
if len(applier.requests()) != 1 {
|
|
t.Fatalf("the role was called %d times, want 1 — the path reached another handler", len(applier.requests()))
|
|
}
|
|
}
|
|
|
|
// TestApplyBatchForwardsEveryLevelOfTheDocumentedBody is the operation's central
|
|
// pin. The body is four levels deep and each level is projected by hand, so this
|
|
// drives one item of every kind at once and asserts the whole request the role
|
|
// received.
|
|
func TestApplyBatchForwardsEveryLevelOfTheDocumentedBody(t *testing.T) {
|
|
applier := &roleBatchApplier{}
|
|
ts := newApplyBatchServer(t, applier)
|
|
|
|
resp := ts.claim(t, batchApplyPath, `{
|
|
"actor": " alice ",
|
|
"provenance": "planner",
|
|
"force_id_prefix": true,
|
|
"skip_per_edge_cycle_check": true,
|
|
"items": [
|
|
{"kind":"create","create":{
|
|
"key":"root","title":"the plan","description":"body","design":"how",
|
|
"acceptance_criteria":"done when","notes":"scratch","issue_type":"task",
|
|
"status":"open","priority":1,"assignee":"bob","owner":"carol",
|
|
"labels":["api","wire"],"estimated_minutes":30,"external_ref":"gh-9",
|
|
"due_at":"2026-01-02T03:04:05Z","defer_until":"2026-01-01T00:00:00Z",
|
|
"sender":"planner","metadata":{"plan":true},"ephemeral":true,
|
|
"metadata_refs":{"retry_of":{"key":"root"}}}},
|
|
{"kind":"update","update":{
|
|
"target":{"key":"root"},
|
|
"expected_status":"open","expected_assignee":"bob",
|
|
"force_close_policy":true,"force_assignee_transfer":true,"force_notes_overwrite":true,
|
|
"patch":{"title":"renamed","status":"closed","assignee":"dave","owner":"erin","notes":"replacement",
|
|
"labels":{"replace":["a"],"add":["b"],"remove":["c"]},
|
|
"metadata":{"set":{"k":null},"unset":["old"]},
|
|
"estimated_minutes":null}}},
|
|
{"kind":"close","close":{
|
|
"target":{"id":"bd-7"},"reason":"done","session":"s-1","force":true,
|
|
"expected_version":"42"}},
|
|
{"kind":"dep_add","dep_add":{
|
|
"source":{"key":"root"},"target":{"id":"bd-7"},"type":"waits-for",
|
|
"metadata":{"gate":"any-children"},"has_spawner":true,"thread_id":"th-plan"}}
|
|
]
|
|
}`)
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
|
}
|
|
reqs := applier.requests()
|
|
if len(reqs) != 1 {
|
|
t.Fatalf("the role was called %d times, want 1", len(reqs))
|
|
}
|
|
got := reqs[0]
|
|
|
|
if got.Actor != "alice" {
|
|
t.Errorf("Actor = %q, want the trimmed value", got.Actor)
|
|
}
|
|
if got.Provenance != "planner" {
|
|
t.Errorf("Provenance = %q, want the body's label", got.Provenance)
|
|
}
|
|
if !got.ForceIDPrefix || !got.SkipPerEdgeCycleCheck {
|
|
t.Errorf("ForceIDPrefix/SkipPerEdgeCycleCheck = %v/%v, want both true",
|
|
got.ForceIDPrefix, got.SkipPerEdgeCycleCheck)
|
|
}
|
|
if len(got.Items) != 4 {
|
|
t.Fatalf("Items = %d, want the four the request declared IN ORDER", len(got.Items))
|
|
}
|
|
for i, want := range []issueops.ItemKind{issueops.ItemCreate, issueops.ItemUpdate, issueops.ItemClose, issueops.ItemDepAdd} {
|
|
if got.Items[i].Kind != want {
|
|
t.Fatalf("Items[%d].Kind = %q, want %q: order is the contract and is never changed", i, got.Items[i].Kind, want)
|
|
}
|
|
}
|
|
|
|
create := got.Items[0].Create
|
|
if create == nil || create.Issue == nil {
|
|
t.Fatalf("Items[0].Create = %v, want the create payload", create)
|
|
}
|
|
if create.Key != "root" {
|
|
t.Errorf("Create.Key = %q, want the name the item gave itself", create.Key)
|
|
}
|
|
for _, check := range []struct {
|
|
member string
|
|
got, want string
|
|
}{
|
|
{"title", create.Issue.Title, "the plan"},
|
|
{"description", create.Issue.Description, "body"},
|
|
{"design", create.Issue.Design, "how"},
|
|
{"acceptance_criteria", create.Issue.AcceptanceCriteria, "done when"},
|
|
{"notes", create.Issue.Notes, "scratch"},
|
|
{"issue_type", string(create.Issue.IssueType), "task"},
|
|
{"status", string(create.Issue.Status), "open"},
|
|
{"assignee", create.Issue.Assignee, "bob"},
|
|
{"owner", create.Issue.Owner, "carol"},
|
|
{"sender", create.Issue.Sender, "planner"},
|
|
} {
|
|
if check.got != check.want {
|
|
t.Errorf("create.%s = %q, want %q", check.member, check.got, check.want)
|
|
}
|
|
}
|
|
if create.Issue.Priority != 1 {
|
|
t.Errorf("create.priority = %d, want 1", create.Issue.Priority)
|
|
}
|
|
// created_by is not the handler's to stamp: the item reaches the role
|
|
// without one, and the role defaults it to the request's actor
|
|
// (backend/conformance's batch-apply contract pins that half).
|
|
if create.Issue.CreatedBy != "" {
|
|
t.Errorf("create.created_by = %q, want it left to the role", create.Issue.CreatedBy)
|
|
}
|
|
if create.Issue.EstimatedMinutes == nil || *create.Issue.EstimatedMinutes != 30 {
|
|
t.Errorf("create.estimated_minutes = %v, want 30", create.Issue.EstimatedMinutes)
|
|
}
|
|
if create.Issue.ExternalRef == nil || *create.Issue.ExternalRef != "gh-9" {
|
|
t.Errorf("create.external_ref = %v, want gh-9", create.Issue.ExternalRef)
|
|
}
|
|
if create.Issue.DueAt == nil || create.Issue.DeferUntil == nil {
|
|
t.Errorf("create.due_at/defer_until = %v/%v, want both parsed", create.Issue.DueAt, create.Issue.DeferUntil)
|
|
}
|
|
if !create.Issue.Ephemeral {
|
|
t.Error("create.ephemeral = false; ephemerality is per item and the request asked for it")
|
|
}
|
|
// The metadata document reaches the role as the caller's own BYTES. A
|
|
// handler that decoded and re-marshaled it would renormalize the caller's
|
|
// numbers, which is the hazard the metadata plane's own operation documents.
|
|
if string(create.Issue.Metadata) != `{"plan":true}` {
|
|
t.Errorf("create.metadata = %s, want the caller's bytes unaltered", create.Issue.Metadata)
|
|
}
|
|
if ref, ok := create.MetadataRefs["retry_of"]; !ok || ref.Key != "root" {
|
|
t.Errorf("create.metadata_refs = %v, want the forward/self reference this member alone may carry", create.MetadataRefs)
|
|
}
|
|
|
|
update := got.Items[1].Update
|
|
if update == nil {
|
|
t.Fatal("Items[1].Update is nil")
|
|
}
|
|
if update.Target.Key != "root" || update.Target.ID != "" {
|
|
t.Errorf("update.target = %+v, want the backward key ref", update.Target)
|
|
}
|
|
if update.ExpectedStatus == nil || string(*update.ExpectedStatus) != "open" {
|
|
t.Errorf("update.expected_status = %v, want open", update.ExpectedStatus)
|
|
}
|
|
if update.ExpectedAssignee == nil || *update.ExpectedAssignee != "bob" {
|
|
t.Errorf("update.expected_assignee = %v, want bob", update.ExpectedAssignee)
|
|
}
|
|
if !update.ForceClosePolicy || !update.ForceAssigneeTransfer || !update.ForceNotesOverwrite {
|
|
t.Errorf("update force flags = %v/%v/%v, want all three true",
|
|
update.ForceClosePolicy, update.ForceAssigneeTransfer, update.ForceNotesOverwrite)
|
|
}
|
|
if !update.Patch.Notes.Set || update.Patch.Notes.Value != "replacement" {
|
|
t.Errorf("update.patch.notes = %+v, want replacement", update.Patch.Notes)
|
|
}
|
|
if !update.Patch.Status.Set || string(update.Patch.Status.Value) != "closed" {
|
|
t.Errorf("update.patch.status = %+v, want the crossing status this operation publishes", update.Patch.Status)
|
|
}
|
|
if !update.Patch.Assignee.Set || update.Patch.Assignee.Value != "dave" {
|
|
t.Errorf("update.patch.assignee = %+v, want dave", update.Patch.Assignee)
|
|
}
|
|
if !update.Patch.Owner.Set || update.Patch.Owner.Value != "erin" {
|
|
t.Errorf("update.patch.owner = %+v, want erin", update.Patch.Owner)
|
|
}
|
|
// The FULL label patch: removal has to be expressible, which is the whole
|
|
// reason this member is not the update operation's plain replacement array.
|
|
labels := update.Patch.Labels
|
|
if !labels.Replace.Set || len(labels.Replace.Value) != 1 || len(labels.Add) != 1 || len(labels.Remove) != 1 {
|
|
t.Errorf("update.patch.labels = %+v, want replace, add and remove all carried", labels)
|
|
}
|
|
if got, ok := update.Patch.Metadata.Set["k"]; !ok || string(got) != "null" {
|
|
t.Errorf("update.patch.metadata.set[k] = %s, want the literal null: a present null is a VALUE", got)
|
|
}
|
|
if len(update.Patch.Metadata.Unset) != 1 || update.Patch.Metadata.Unset[0] != "old" {
|
|
t.Errorf("update.patch.metadata.unset = %v, want [old]", update.Patch.Metadata.Unset)
|
|
}
|
|
// An explicit null on a nullable patch member is a CLEAR, not an omission.
|
|
if !update.Patch.EstimatedMinutes.Set || update.Patch.EstimatedMinutes.Value != nil {
|
|
t.Errorf("update.patch.estimated_minutes = %+v, want set with a nil value (a clear)", update.Patch.EstimatedMinutes)
|
|
}
|
|
|
|
closeItem := got.Items[2].Close
|
|
if closeItem == nil {
|
|
t.Fatal("Items[2].Close is nil")
|
|
}
|
|
if closeItem.Target.ID != "bd-7" || closeItem.Reason != "done" || closeItem.Session != "s-1" || !closeItem.Force {
|
|
t.Errorf("close = %+v, want the four members the document publishes", closeItem)
|
|
}
|
|
if closeItem.ExpectedVersion == nil || *closeItem.ExpectedVersion != 42 {
|
|
t.Errorf("close.expected_version = %v, want 42", closeItem.ExpectedVersion)
|
|
}
|
|
|
|
depAdd := got.Items[3].DepAdd
|
|
if depAdd == nil {
|
|
t.Fatal("Items[3].DepAdd is nil")
|
|
}
|
|
if depAdd.Source.Key != "root" || depAdd.Target.ID != "bd-7" || string(depAdd.Type) != "waits-for" {
|
|
t.Errorf("dep_add = %+v, want the edge the request spelled", depAdd)
|
|
}
|
|
// The gate blob travels as bytes. Normalizing it is the ROLE's, and a
|
|
// handler that parsed it would be a second definition of what a gate is.
|
|
if depAdd.Metadata != `{"gate":"any-children"}` {
|
|
t.Errorf("dep_add.metadata = %q, want the caller's bytes unaltered", depAdd.Metadata)
|
|
}
|
|
// The lineage members reach the role as sent: issues.batchApply.depAddLineage
|
|
// gates whether a CLIENT sends them, and this server always reads them.
|
|
if !depAdd.HasSpawner || depAdd.ThreadID != "th-plan" {
|
|
t.Errorf("dep_add.has_spawner/thread_id = %v/%q, want true/%q", depAdd.HasSpawner, depAdd.ThreadID, "th-plan")
|
|
}
|
|
}
|
|
|
|
// TestApplyBatchAnswersWithTheLeanResult pins the response side: ids, a
|
|
// revision and nothing else. A hydrated issue here would be a response an order
|
|
// of magnitude larger than the request, for a snapshot only the library's hooks
|
|
// consume — and hooks never fire on this surface.
|
|
func TestApplyBatchAnswersWithTheLeanResult(t *testing.T) {
|
|
applier := &roleBatchApplier{result: issueops.ApplyBatchResult{
|
|
Keys: map[string]string{"root": "bd-1"},
|
|
Items: []issueops.ItemResult{
|
|
{Kind: issueops.ItemCreate, IssueID: "bd-1", Changed: true, RowVersion: 77,
|
|
Issue: seededIssue("bd-1", "alice", "open")},
|
|
{Kind: issueops.ItemDepAdd, IssueID: "bd-1", DependsOnID: "bd-7", Changed: false},
|
|
},
|
|
}}
|
|
ts := newApplyBatchServer(t, applier)
|
|
|
|
resp := ts.claim(t, batchApplyPath, `{"actor":"alice","items":[{"kind":"create","create":{"title":"one"}}]}`)
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
|
}
|
|
body := decodeBody(t, resp)
|
|
keys, _ := body["keys"].(map[string]any)
|
|
if keys["root"] != "bd-1" {
|
|
t.Errorf("keys = %v, want the one fact the request cannot carry", body["keys"])
|
|
}
|
|
items, _ := body["items"].([]any)
|
|
if len(items) != 2 {
|
|
t.Fatalf("items = %v, want one entry per requested item", body["items"])
|
|
}
|
|
first, _ := items[0].(map[string]any)
|
|
if first["kind"] != "create" || first["issue_id"] != "bd-1" || first["changed"] != true {
|
|
t.Errorf("items[0] = %v, want the item's kind, id and changed flag", first)
|
|
}
|
|
if first["revision"] != "77" {
|
|
t.Errorf("items[0].revision = %v, want the row's token as a decimal string", first["revision"])
|
|
}
|
|
if _, present := first["issue"]; present {
|
|
t.Error("items[0] carries a hydrated issue; the wire result is lean and the snapshot stops at the library boundary")
|
|
}
|
|
if _, present := first["depends_on_id"]; present {
|
|
t.Error("items[0] carries depends_on_id; it is a dep_add member and its ABSENCE is how a client tells the kinds apart")
|
|
}
|
|
second, _ := items[1].(map[string]any)
|
|
if second["depends_on_id"] != "bd-7" {
|
|
t.Errorf("items[1].depends_on_id = %v, want the edge's target", second["depends_on_id"])
|
|
}
|
|
// 0 is a real value — a legacy row, and every dep_add — so the member is
|
|
// emitted rather than omitted, or a client could not tell the two apart.
|
|
if second["revision"] != "0" {
|
|
t.Errorf("items[1].revision = %v, want \"0\" emitted rather than omitted", second["revision"])
|
|
}
|
|
}
|
|
|
|
// TestApplyBatchAnswersAnEmptyKeysObjectRatherThanNull: `keys` is a required
|
|
// member, and a request whose creates named nothing must not answer with the
|
|
// `null` a nil Go map marshals to.
|
|
func TestApplyBatchAnswersAnEmptyKeysObjectRatherThanNull(t *testing.T) {
|
|
applier := &roleBatchApplier{result: issueops.ApplyBatchResult{
|
|
Items: []issueops.ItemResult{{Kind: issueops.ItemCreate, IssueID: "bd-1", Changed: true}},
|
|
}}
|
|
ts := newApplyBatchServer(t, applier)
|
|
|
|
resp := ts.claim(t, batchApplyPath, `{"actor":"alice","items":[{"kind":"create","create":{"title":"one"}}]}`)
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
|
|
}
|
|
raw := decodeBody(t, resp)
|
|
keys, ok := raw["keys"].(map[string]any)
|
|
if !ok || len(keys) != 0 {
|
|
t.Errorf("keys = %v, want an empty object for a request whose creates named nothing", raw["keys"])
|
|
}
|
|
}
|
|
|
|
// TestApplyBatchRefusesAnUnknownMemberAtEveryLevel is the gate the four-level
|
|
// body needs most. Each schema is additionalProperties: false, and a level whose
|
|
// unknown member slid through would be undisclosed write surface — so every
|
|
// level is driven, and the refusal must name the offender by its qualified path.
|
|
func TestApplyBatchRefusesAnUnknownMemberAtEveryLevel(t *testing.T) {
|
|
for _, test := range []struct {
|
|
name string
|
|
body string
|
|
wantParam string
|
|
}{
|
|
{
|
|
name: "request",
|
|
body: `{"actor":"alice","nope":1,"items":[{"kind":"create","create":{"title":"one"}}]}`,
|
|
wantParam: "nope",
|
|
},
|
|
{
|
|
name: "item",
|
|
body: `{"actor":"alice","items":[{"kind":"create","nope":1,"create":{"title":"one"}}]}`,
|
|
wantParam: "items[0].nope",
|
|
},
|
|
{
|
|
name: "create payload",
|
|
body: `{"actor":"alice","items":[{"kind":"create","create":{"title":"one","nope":1}}]}`,
|
|
wantParam: "items[0].create.nope",
|
|
},
|
|
{
|
|
name: "update payload",
|
|
body: `{"actor":"alice","items":[{"kind":"update","update":{"target":{"id":"bd-1"},"patch":{"title":"x"},"nope":1}}]}`,
|
|
wantParam: "items[0].update.nope",
|
|
},
|
|
{
|
|
name: "patch",
|
|
body: `{"actor":"alice","items":[{"kind":"update","update":{"target":{"id":"bd-1"},"patch":{"nope":1}}}]}`,
|
|
wantParam: "items[0].update.patch.nope",
|
|
},
|
|
{
|
|
name: "label patch",
|
|
body: `{"actor":"alice","items":[{"kind":"update","update":{"target":{"id":"bd-1"},"patch":{"labels":{"nope":[]}}}}]}`,
|
|
wantParam: "items[0].update.patch.labels.nope",
|
|
},
|
|
{
|
|
name: "metadata patch",
|
|
body: `{"actor":"alice","items":[{"kind":"update","update":{"target":{"id":"bd-1"},"patch":{"metadata":{"nope":1}}}}]}`,
|
|
wantParam: "items[0].update.patch.metadata.nope",
|
|
},
|
|
{
|
|
name: "close payload",
|
|
body: `{"actor":"alice","items":[{"kind":"close","close":{"target":{"id":"bd-1"},"nope":1}}]}`,
|
|
wantParam: "items[0].close.nope",
|
|
},
|
|
{
|
|
name: "dep_add payload",
|
|
body: `{"actor":"alice","items":[{"kind":"dep_add","dep_add":{"source":{"id":"a"},"target":{"id":"b"},"type":"blocks","nope":1}}]}`,
|
|
wantParam: "items[0].dep_add.nope",
|
|
},
|
|
{
|
|
name: "ref",
|
|
body: `{"actor":"alice","items":[{"kind":"close","close":{"target":{"id":"bd-1","nope":1}}}]}`,
|
|
wantParam: "items[0].close.target.nope",
|
|
},
|
|
{
|
|
name: "metadata ref",
|
|
body: `{"actor":"alice","items":[{"kind":"create","create":{"title":"one","metadata_refs":{"r":{"key":"k","nope":1}}}}]}`,
|
|
wantParam: "items[0].create.metadata_refs.r.nope",
|
|
},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
applier := &roleBatchApplier{}
|
|
ts := newApplyBatchServer(t, applier)
|
|
|
|
resp := ts.claim(t, batchApplyPath, 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["param"] != test.wantParam {
|
|
t.Errorf("param = %v, want %q: a client learns WHICH level and WHICH member from this alone",
|
|
body["param"], test.wantParam)
|
|
}
|
|
if body["reason"] != "unknown_parameter" {
|
|
t.Errorf("reason = %v, want unknown_parameter", body["reason"])
|
|
}
|
|
if len(applier.requests()) != 0 {
|
|
t.Errorf("the role was called for a refused request; nothing may reach it")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestApplyBatchRefusesATagThatDisagreesWithItsPayload is the case the document
|
|
// cannot express and the server therefore owns. The item is a tagged
|
|
// single-shape object because this document uses no composition keyword, so
|
|
// nothing in a generated type stops a client from sending a kind and another
|
|
// kind's payload — or two payloads, or none.
|
|
func TestApplyBatchRefusesATagThatDisagreesWithItsPayload(t *testing.T) {
|
|
for _, test := range []struct {
|
|
name string
|
|
item string
|
|
wantParam string
|
|
}{
|
|
{
|
|
name: "kind says create, payload is update",
|
|
item: `{"kind":"create","update":{"target":{"id":"bd-1"},"patch":{"title":"x"}}}`,
|
|
wantParam: "items[0].update",
|
|
},
|
|
{
|
|
name: "kind names no payload",
|
|
item: `{"kind":"create"}`,
|
|
wantParam: "items[0].create",
|
|
},
|
|
{
|
|
// The offender is the payload the kind does NOT name, chosen in a
|
|
// fixed order so `param` never depends on map iteration.
|
|
name: "two payloads",
|
|
item: `{"kind":"create","create":{"title":"one"},"close":{"target":{"id":"bd-1"}}}`,
|
|
wantParam: "items[0].close",
|
|
},
|
|
{
|
|
name: "kind outside the enum",
|
|
item: `{"kind":"reopen","create":{"title":"one"}}`,
|
|
wantParam: "items[0].kind",
|
|
},
|
|
{
|
|
name: "no kind at all",
|
|
item: `{"create":{"title":"one"}}`,
|
|
wantParam: "items[0].kind",
|
|
},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
applier := &roleBatchApplier{}
|
|
ts := newApplyBatchServer(t, applier)
|
|
|
|
resp := ts.claim(t, batchApplyPath, `{"actor":"alice","items":[`+test.item+`]}`)
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
|
|
}
|
|
body := decodeBody(t, resp)
|
|
if body["param"] != test.wantParam {
|
|
t.Errorf("param = %v, want %q: a client must never have to read prose to find the offender",
|
|
body["param"], test.wantParam)
|
|
}
|
|
if len(applier.requests()) != 0 {
|
|
t.Error("the role was called for an item whose halves disagree")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestApplyBatchRejectsTheShapesTheDocumentRefuses pins the rest of the 400s,
|
|
// each of them before the role is reached: a request the handler refuses must
|
|
// not become a call the role has to refuse again.
|
|
func TestApplyBatchRejectsTheShapesTheDocumentRefuses(t *testing.T) {
|
|
item := func(payload string) string {
|
|
return `{"actor":"alice","items":[` + payload + `]}`
|
|
}
|
|
oversize := make([]byte, 0, 300)
|
|
for range 300 {
|
|
oversize = append(oversize, 'x')
|
|
}
|
|
for _, test := range []struct {
|
|
name string
|
|
body string
|
|
}{
|
|
{"missing actor", `{"items":[{"kind":"create","create":{"title":"one"}}]}`},
|
|
{"null actor", `{"actor":null,"items":[{"kind":"create","create":{"title":"one"}}]}`},
|
|
{"blank actor", `{"actor":" ","items":[{"kind":"create","create":{"title":"one"}}]}`},
|
|
{"missing items", `{"actor":"alice"}`},
|
|
{"empty items", `{"actor":"alice","items":[]}`},
|
|
{"items is not an array", `{"actor":"alice","items":{}}`},
|
|
{"an item is not an object", `{"actor":"alice","items":[3]}`},
|
|
{"non-object body", `[]`},
|
|
{"unparseable body", `{`},
|
|
{"create with no title", item(`{"kind":"create","create":{}}`)},
|
|
{"create with a blank title", item(`{"kind":"create","create":{"title":" "}}`)},
|
|
{"create with an oversize title", item(`{"kind":"create","create":{"title":"` + string(oversize) + `"}}`)},
|
|
{"create with a control character in the assignee", item(`{"kind":"create","create":{"title":"t","assignee":"a\u0007b"}}`)},
|
|
{"create priority out of range", item(`{"kind":"create","create":{"title":"t","priority":9}}`)},
|
|
{"create priority of the wrong type", item(`{"kind":"create","create":{"title":"t","priority":"high"}}`)},
|
|
{"create on both planes", item(`{"kind":"create","create":{"title":"t","ephemeral":true,"no_history":true}}`)},
|
|
{"update with no target", item(`{"kind":"update","update":{"patch":{"title":"x"}}}`)},
|
|
{"update with an empty patch", item(`{"kind":"update","update":{"target":{"id":"bd-1"},"patch":{}}}`)},
|
|
{"update with no patch", item(`{"kind":"update","update":{"target":{"id":"bd-1"}}}`)},
|
|
{"a null on a non-nullable patch member", item(`{"kind":"update","update":{"target":{"id":"bd-1"},"patch":{"title":null}}}`)},
|
|
{"notes and append_notes together", item(`{"kind":"update","update":{"target":{"id":"bd-1"},"patch":{"notes":"a","append_notes":"b"}}}`)},
|
|
{"metadata replace beside a merge", item(`{"kind":"update","update":{"target":{"id":"bd-1"},"patch":{"metadata":{"replace":{},"merge":{"a":1}}}}}`)},
|
|
{"a ref naming both a key and an id", item(`{"kind":"close","close":{"target":{"key":"k","id":"bd-1"}}}`)},
|
|
{"a ref naming neither", item(`{"kind":"close","close":{"target":{}}}`)},
|
|
{"a ref that is not an object", item(`{"kind":"close","close":{"target":"bd-1"}}`)},
|
|
{"dep_add with no type", item(`{"kind":"dep_add","dep_add":{"source":{"id":"a"},"target":{"id":"b"}}}`)},
|
|
{"dep_add with an empty type", item(`{"kind":"dep_add","dep_add":{"source":{"id":"a"},"target":{"id":"b"},"type":""}}`)},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
applier := &roleBatchApplier{}
|
|
ts := newApplyBatchServer(t, applier)
|
|
|
|
resp := ts.claim(t, batchApplyPath, test.body)
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
|
|
}
|
|
if len(applier.requests()) != 0 {
|
|
t.Errorf("the role was called %d times for a refused request, want 0", len(applier.requests()))
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestApplyBatchRefusesAnEmptyThreadID pins the document's minLength: 1 on a
|
|
// dep_add item's thread_id. An absent member already names no thread, so an
|
|
// empty one is refused by name rather than read as a second spelling of it.
|
|
// The client never sends one (setItemString omits an empty value), so only a
|
|
// direct-wire caller reaches this.
|
|
func TestApplyBatchRefusesAnEmptyThreadID(t *testing.T) {
|
|
applier := &roleBatchApplier{}
|
|
ts := newApplyBatchServer(t, applier)
|
|
|
|
resp := ts.claim(t, batchApplyPath, `{"actor":"alice","items":[{"kind":"dep_add","dep_add":{
|
|
"source":{"id":"a"},"target":{"id":"b"},"type":"blocks","thread_id":""}}]}`)
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
|
|
}
|
|
body := decodeBody(t, resp)
|
|
if body["param"] != "items[0].dep_add.thread_id" || body["reason"] != "invalid_value" {
|
|
t.Errorf("param/reason = %v/%v, want items[0].dep_add.thread_id/invalid_value", body["param"], body["reason"])
|
|
}
|
|
if len(applier.requests()) != 0 {
|
|
t.Errorf("the role was called for a refused request; nothing may reach it")
|
|
}
|
|
}
|
|
|
|
// TestApplyBatchRefusesMoreItemsThanTheRoleAccepts pins the cap at the edge, so
|
|
// an over-long plan costs no database work. The number is the role's own
|
|
// constant rather than a second copy of it.
|
|
func TestApplyBatchRefusesMoreItemsThanTheRoleAccepts(t *testing.T) {
|
|
applier := &roleBatchApplier{}
|
|
ts := newApplyBatchServer(t, applier)
|
|
|
|
body := `{"actor":"alice","items":[`
|
|
for i := range issueops.MaxApplyBatchItems + 1 {
|
|
if i > 0 {
|
|
body += ","
|
|
}
|
|
body += fmt.Sprintf(`{"kind":"create","create":{"title":"i%d"}}`, i)
|
|
}
|
|
body += `]}`
|
|
|
|
resp := ts.claim(t, batchApplyPath, body)
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
|
|
}
|
|
if decodeBody(t, resp)["param"] != "items" {
|
|
t.Error("the refusal does not name `items`")
|
|
}
|
|
if len(applier.requests()) != 0 {
|
|
t.Error("an over-long plan reached the role")
|
|
}
|
|
}
|
|
|
|
// TestApplyBatchRefusesAQueryParameterAndAForeignMediaType keeps this operation
|
|
// on the surface's two shared refusals rather than letting a new handler quietly
|
|
// opt out of them.
|
|
func TestApplyBatchRefusesAQueryParameterAndAForeignMediaType(t *testing.T) {
|
|
applier := &roleBatchApplier{}
|
|
ts := newApplyBatchServer(t, applier)
|
|
|
|
body := `{"actor":"alice","items":[{"kind":"create","create":{"title":"one"}}]}`
|
|
if resp := ts.claim(t, batchApplyPath+"?verbose=1", body); resp.StatusCode != http.StatusBadRequest {
|
|
t.Errorf("status with a query parameter = %d, want 400", resp.StatusCode)
|
|
}
|
|
if resp := ts.postBody(t, batchApplyPath, "text/plain", body); resp.StatusCode != http.StatusBadRequest {
|
|
t.Errorf("status with a foreign media type = %d, want 400", resp.StatusCode)
|
|
}
|
|
if len(applier.requests()) != 0 {
|
|
t.Errorf("the role was called %d times for refused requests, want 0", len(applier.requests()))
|
|
}
|
|
}
|
|
|
|
// TestApplyBatchReportsAForwardKeyReferenceAsAnOrderingMistake is the pin on
|
|
// the one 400 that carries a discriminator. A key declared LATER is an ORDERING
|
|
// mistake and a key nothing declares is a typo, and a client that could not tell
|
|
// them apart would go hunting for a misspelling in a request that is spelled
|
|
// correctly and ordered wrongly.
|
|
func TestApplyBatchReportsAForwardKeyReferenceAsAnOrderingMistake(t *testing.T) {
|
|
for _, test := range []struct {
|
|
name string
|
|
err error
|
|
wantDeclaredLater bool
|
|
wantParam string
|
|
}{
|
|
{
|
|
name: "declared later",
|
|
err: &issueops.RefError{Index: 1, Member: "target", Key: "late", DeclaredLater: true},
|
|
wantDeclaredLater: true,
|
|
wantParam: "items[1].update.target",
|
|
},
|
|
{
|
|
name: "declared nowhere",
|
|
err: &issueops.RefError{Index: 1, Member: "target", Key: "typo"},
|
|
wantDeclaredLater: false,
|
|
wantParam: "items[1].update.target",
|
|
},
|
|
{
|
|
name: "a metadata ref names the free-form member",
|
|
err: &issueops.RefError{Index: 0, Member: "metadata_ref retry_of", Key: "typo"},
|
|
wantDeclaredLater: false,
|
|
wantParam: "items[0].create.metadata_refs",
|
|
},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
applier := &roleBatchApplier{err: test.err}
|
|
ts := newApplyBatchServer(t, applier)
|
|
|
|
resp := ts.claim(t, batchApplyPath, `{"actor":"alice","items":[
|
|
{"kind":"create","create":{"title":"one","metadata_refs":{"retry_of":{"key":"typo"}}}},
|
|
{"kind":"update","update":{"target":{"key":"late"},"patch":{"title":"x"}}}
|
|
]}`)
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("status = %d, want 400: %s", resp.StatusCode, readAll(t, resp))
|
|
}
|
|
body := decodeBody(t, resp)
|
|
if body["code"] != "invalid_argument" {
|
|
t.Errorf("code = %v, want invalid_argument", body["code"])
|
|
}
|
|
declaredLater, present := body["declared_later"]
|
|
if !present {
|
|
t.Fatal("declared_later is absent; both polarities are emitted, so a client can never read absence as false")
|
|
}
|
|
if declaredLater != test.wantDeclaredLater {
|
|
t.Errorf("declared_later = %v, want %v", declaredLater, test.wantDeclaredLater)
|
|
}
|
|
if body["param"] != test.wantParam {
|
|
t.Errorf("param = %v, want %q", body["param"], test.wantParam)
|
|
}
|
|
// RefError.Member is diagnostic prose, so it is mapped onto the
|
|
// document's member names and never published as a value.
|
|
if _, present := body["member"]; present {
|
|
t.Error("the problem carries a `member`; the role's free-form member name is not wire vocabulary")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestApplyBatchReportsAPreconditionMissAsAConflict is the operation's posture
|
|
// pin, and the difference from the metadata compare-and-set stated as a test: a
|
|
// guard that missed took the WHOLE request down, so it belongs in the error
|
|
// channel carrying the members that name the item.
|
|
func TestApplyBatchReportsAPreconditionMissAsAConflict(t *testing.T) {
|
|
for _, test := range []struct {
|
|
name string
|
|
err error
|
|
wantParam string
|
|
assert func(t *testing.T, body map[string]any)
|
|
}{
|
|
{
|
|
name: "version",
|
|
err: itemErr(1, issueops.ItemUpdate, "root", "bd-1", issueops.ErrVersionMismatch),
|
|
wantParam: "items[1].update.expected_version",
|
|
assert: func(t *testing.T, body map[string]any) {
|
|
if body["expected_version"] != "42" {
|
|
t.Errorf("expected_version = %v, want the guard the request sent, echoed as the string it arrived as", body["expected_version"])
|
|
}
|
|
},
|
|
},
|
|
{
|
|
name: "status",
|
|
err: itemErr(1, issueops.ItemUpdate, "root", "bd-1", issueops.ErrStatusMismatch),
|
|
wantParam: "items[1].update.expected_status",
|
|
assert: func(t *testing.T, body map[string]any) {
|
|
if body["expected_status"] != "open" {
|
|
t.Errorf("expected_status = %v, want the guard the request sent", body["expected_status"])
|
|
}
|
|
},
|
|
},
|
|
{
|
|
name: "assignee",
|
|
err: itemErr(1, issueops.ItemUpdate, "root", "bd-1", issueops.ErrAssigneeMismatch),
|
|
wantParam: "items[1].update.expected_assignee",
|
|
assert: func(t *testing.T, body map[string]any) {
|
|
if body["expected_assignee"] != "bob" {
|
|
t.Errorf("expected_assignee = %v, want the guard the request sent", body["expected_assignee"])
|
|
}
|
|
},
|
|
},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
applier := &roleBatchApplier{err: test.err}
|
|
ts := newApplyBatchServer(t, applier)
|
|
|
|
resp := ts.claim(t, batchApplyPath, `{"actor":"alice","items":[
|
|
{"kind":"create","create":{"key":"root","title":"one"}},
|
|
{"kind":"update","update":{"target":{"id":"bd-1"},
|
|
"expected_version":"42","expected_status":"open","expected_assignee":"bob",
|
|
"patch":{"title":"x"}}}
|
|
]}`)
|
|
if resp.StatusCode != http.StatusConflict {
|
|
t.Fatalf("status = %d, want 409: a miss refuses the whole request, so it is not an answer here: %s",
|
|
resp.StatusCode, readAll(t, resp))
|
|
}
|
|
body := decodeBody(t, resp)
|
|
if body["code"] != "precondition_failed" {
|
|
t.Fatalf("code = %v, want precondition_failed", body["code"])
|
|
}
|
|
if body["item_index"] != float64(1) || body["item_kind"] != "update" {
|
|
t.Errorf("item_index/item_kind = %v/%v, want 1/update: the only place the offender exists",
|
|
body["item_index"], body["item_kind"])
|
|
}
|
|
if body["item_key"] != "root" {
|
|
t.Errorf("item_key = %v, want the key the refused item named", body["item_key"])
|
|
}
|
|
// item_issue_id, NOT issue_id: that name is already the hierarchy
|
|
// refusal's presence discriminator.
|
|
if body["item_issue_id"] != "bd-1" {
|
|
t.Errorf("item_issue_id = %v, want the resolved id", body["item_issue_id"])
|
|
}
|
|
if _, present := body["issue_id"]; present {
|
|
t.Error("the problem carries `issue_id`; that member discriminates the dependency_cycle hierarchy refusal and must not fire here")
|
|
}
|
|
if body["param"] != test.wantParam {
|
|
t.Errorf("param = %v, want %q", body["param"], test.wantParam)
|
|
}
|
|
// The refusal rolled its transaction back, so there is no observed
|
|
// value this operation could honestly report.
|
|
for _, absent := range []string{"actual_version", "actual_status", "actual_assignee"} {
|
|
if _, present := body[absent]; present {
|
|
t.Errorf("the problem carries %s; the refusal saw a row that no longer exists to read", absent)
|
|
}
|
|
}
|
|
test.assert(t, body)
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestApplyBatchRefusesANumericVersionGuard pins the one spelling of the guard
|
|
// on the batch surface, on BOTH item kinds that carry it.
|
|
//
|
|
// `expected_version` is a decimal string, and a bare number is refused rather
|
|
// than coerced. There is no transitional number-or-string acceptance on purpose:
|
|
// a number is the shape a double-based client has ALREADY rounded by the time it
|
|
// leaves the client, so taking it would mean guarding on a token the server
|
|
// never minted and refusing a row nobody touched — the exact failure the string
|
|
// exists to remove. The update arm also pins the ORDER: the guard is read before
|
|
// the item's typed decode, so a mistyped token earns a 400 naming the member
|
|
// instead of the item-level "wrong JSON type".
|
|
func TestApplyBatchRefusesANumericVersionGuard(t *testing.T) {
|
|
for _, test := range []struct {
|
|
name string
|
|
item string
|
|
wantParam string
|
|
}{
|
|
{
|
|
name: "update",
|
|
item: `{"kind":"update","update":{"target":{"id":"bd-1"},"expected_version":42,"patch":{"title":"x"}}}`,
|
|
wantParam: "items[0].update.expected_version",
|
|
},
|
|
{
|
|
name: "update past 2^53",
|
|
item: `{"kind":"update","update":{"target":{"id":"bd-1"},"expected_version":9007199254740993,"patch":{"title":"x"}}}`,
|
|
wantParam: "items[0].update.expected_version",
|
|
},
|
|
{
|
|
name: "close",
|
|
item: `{"kind":"close","close":{"target":{"id":"bd-1"},"expected_version":42}}`,
|
|
wantParam: "items[0].close.expected_version",
|
|
},
|
|
{
|
|
name: "a string that is not a decimal token",
|
|
item: `{"kind":"update","update":{"target":{"id":"bd-1"},"expected_version":"forty-two","patch":{"title":"x"}}}`,
|
|
wantParam: "items[0].update.expected_version",
|
|
},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
applier := &roleBatchApplier{}
|
|
ts := newApplyBatchServer(t, applier)
|
|
|
|
resp := ts.claim(t, batchApplyPath, `{"actor":"alice","items":[`+test.item+`]}`)
|
|
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.wantParam {
|
|
t.Errorf("param = %v, want %q — the refusal must name the member, not the item", body["param"], test.wantParam)
|
|
}
|
|
if calls := applier.requests(); len(calls) != 0 {
|
|
t.Errorf("%d batches reached the role; a malformed guard is refused before any database work", len(calls))
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestApplyBatchMapsTheRolesTypedRefusalsOntoTheDocumentedCodes walks the rest
|
|
// of the refusal table. Every branch reads a TYPED error rather than prose,
|
|
// which is what lets a client stop substring-matching messages.
|
|
func TestApplyBatchMapsTheRolesTypedRefusalsOntoTheDocumentedCodes(t *testing.T) {
|
|
for _, test := range []struct {
|
|
name string
|
|
err error
|
|
wantStatus int
|
|
wantCode string
|
|
wantParam string
|
|
}{
|
|
{
|
|
name: "a scheduling cycle",
|
|
err: itemErr(0, issueops.ItemDepAdd, "", "bd-1", issueops.ErrDependencyCycle),
|
|
wantStatus: http.StatusConflict,
|
|
wantCode: "dependency_cycle",
|
|
},
|
|
{
|
|
name: "a hierarchy conflict",
|
|
err: itemErr(0, issueops.ItemDepAdd, "", "bd-1",
|
|
&issueops.DependencyHierarchyConflictError{IssueID: "bd-1", BlockerID: "bd-2", BlockerIsAncestor: true}),
|
|
wantStatus: http.StatusConflict,
|
|
wantCode: "dependency_cycle",
|
|
},
|
|
{
|
|
name: "a type conflict",
|
|
err: itemErr(0, issueops.ItemDepAdd, "", "bd-1",
|
|
&issueops.DependencyTypeConflictError{ExistingType: "blocks", RequestedType: "parent-child"}),
|
|
wantStatus: http.StatusConflict,
|
|
wantCode: "dependency_exists",
|
|
},
|
|
{
|
|
name: "close policy",
|
|
err: itemErr(0, issueops.ItemClose, "", "bd-1", &issueops.CloseOpenChildrenError{IssueID: "bd-1", OpenChildren: 3}),
|
|
wantStatus: http.StatusConflict,
|
|
wantCode: "not_closable",
|
|
},
|
|
{
|
|
name: "the assignee fence",
|
|
err: itemErr(0, issueops.ItemUpdate, "", "bd-1", storage.ErrAlreadyClaimed),
|
|
wantStatus: http.StatusConflict,
|
|
wantCode: "already_claimed",
|
|
wantParam: "items[0].update.assignee",
|
|
},
|
|
{
|
|
name: "a ghost edge source",
|
|
err: itemErr(0, issueops.ItemDepAdd, "", "", &issueops.DependencyEndpointNotFoundError{
|
|
IssueID: "bd-1", DependsOnID: "bd-2", MissingID: "bd-1", Err: issueops.ErrDependencySourceNotFound,
|
|
}),
|
|
wantStatus: http.StatusBadRequest,
|
|
wantCode: "invalid_argument",
|
|
wantParam: "items[0].dep_add.source",
|
|
},
|
|
{
|
|
name: "a ghost edge target",
|
|
err: itemErr(0, issueops.ItemDepAdd, "", "", &issueops.DependencyEndpointNotFoundError{
|
|
IssueID: "bd-1", DependsOnID: "bd-2", MissingID: "bd-2", Err: issueops.ErrDependencyTargetNotFound,
|
|
}),
|
|
wantStatus: http.StatusBadRequest,
|
|
wantCode: "invalid_argument",
|
|
wantParam: "items[0].dep_add.target",
|
|
},
|
|
{
|
|
// A 409, not a 400: the body is well-formed and stays well-formed —
|
|
// the identical request succeeded before the id was taken — so what
|
|
// refuses it is state the client has to READ, not a request it has
|
|
// to fix. `param` and the item members still name where.
|
|
name: "an occupied explicit id",
|
|
err: itemErr(0, issueops.ItemCreate, "root", "", storage.ErrAlreadyExists),
|
|
wantStatus: http.StatusConflict,
|
|
wantCode: "already_exists",
|
|
wantParam: "items[0].create.id",
|
|
},
|
|
{
|
|
name: "a target that names nothing",
|
|
err: itemErr(0, issueops.ItemUpdate, "", "bd-9", storage.ErrNotFound),
|
|
wantStatus: http.StatusNotFound,
|
|
wantCode: "not_found",
|
|
},
|
|
{
|
|
// The dotted-id hierarchy rule is request validation (it unwraps to
|
|
// ErrValidation), never the hierarchy CONFLICT's dependency_cycle:
|
|
// it is decided from the two resolved ids, ahead of every check that
|
|
// reads the stored graph, so even a child whose parent-child edge IS
|
|
// stored gets this 400, with no hierarchy members to describe.
|
|
name: "a dotted child gated on its own parent",
|
|
err: itemErr(0, issueops.ItemDepAdd, "", "bd-1.1",
|
|
&issueops.DottedChildDependencyError{IssueID: "bd-1.1", DependsOnID: "bd-1", Type: issueops.DepBlocks}),
|
|
wantStatus: http.StatusBadRequest,
|
|
wantCode: "invalid_argument",
|
|
wantParam: "items",
|
|
},
|
|
{
|
|
name: "the workspace's own validation",
|
|
err: itemErr(0, issueops.ItemCreate, "", "", storage.ErrValidation),
|
|
wantStatus: http.StatusBadRequest,
|
|
wantCode: "invalid_argument",
|
|
},
|
|
{
|
|
name: "something the mapping does not know",
|
|
err: errUnmapped,
|
|
wantStatus: http.StatusInternalServerError,
|
|
wantCode: "internal",
|
|
},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
applier := &roleBatchApplier{err: test.err}
|
|
ts := newApplyBatchServer(t, applier)
|
|
|
|
resp := ts.claim(t, batchApplyPath, `{"actor":"alice","items":[{"kind":"create","create":{"title":"one"}}]}`)
|
|
if resp.StatusCode != test.wantStatus {
|
|
t.Fatalf("status = %d, want %d: %s", resp.StatusCode, test.wantStatus, readAll(t, resp))
|
|
}
|
|
body := decodeBody(t, resp)
|
|
if body["code"] != test.wantCode {
|
|
t.Errorf("code = %v, want %q", body["code"], test.wantCode)
|
|
}
|
|
if test.wantParam != "" && body["param"] != test.wantParam {
|
|
t.Errorf("param = %v, want %q", body["param"], test.wantParam)
|
|
}
|
|
if test.wantStatus < 500 && test.wantCode != "internal" {
|
|
if body["item_index"] != float64(0) {
|
|
t.Errorf("item_index = %v, want 0: every refusal that names an item must carry it", body["item_index"])
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// errUnmapped stands in for a refusal the mapping does not know, so the default
|
|
// branch is driven rather than assumed.
|
|
var errUnmapped = fmt.Errorf("a failure this mapping has never seen")
|
|
|
|
// TestApplyBatchNamesTheBlockersOfARefusedClose: the all-or-nothing plan has no
|
|
// per-item result array to carry the refusal in, so the problem document names
|
|
// the offending item AND its blockers, from the same typed list the single
|
|
// close publishes.
|
|
func TestApplyBatchNamesTheBlockersOfARefusedClose(t *testing.T) {
|
|
applier := &roleBatchApplier{err: itemErr(0, issueops.ItemClose, "", "bd-1", blockedCloseFixture())}
|
|
ts := newApplyBatchServer(t, applier)
|
|
|
|
resp := ts.claim(t, batchApplyPath, `{"actor":"alice","items":[{"kind":"create","create":{"title":"one"}}]}`)
|
|
if resp.StatusCode != http.StatusConflict {
|
|
t.Fatalf("status = %d, want 409: %s", resp.StatusCode, readAll(t, resp))
|
|
}
|
|
body := decodeBody(t, resp)
|
|
if body["code"] != string(CodeNotClosable) {
|
|
t.Errorf("code = %v, want %s", body["code"], CodeNotClosable)
|
|
}
|
|
if body["item_index"] != float64(0) {
|
|
t.Errorf("item_index = %v, want 0", body["item_index"])
|
|
}
|
|
assertBlockersMember(t, "problem", body["blockers"])
|
|
if want := blockedCloseSentence + "; clear the blocker, or send the item's force flag"; body["detail"] != want {
|
|
t.Errorf("detail = %q, want %q", body["detail"], want)
|
|
}
|
|
}
|
|
|
|
// TestApplyBatchCarriesTheHierarchyMembersOnlyOnTheHierarchyRefusal pins the
|
|
// discriminator inside `dependency_cycle`: member PRESENCE tells a plain
|
|
// scheduling cycle from the hierarchy case, exactly as it does on
|
|
// POST /v0/beads/dependencies:add.
|
|
func TestApplyBatchCarriesTheHierarchyMembersOnlyOnTheHierarchyRefusal(t *testing.T) {
|
|
hierarchy := &roleBatchApplier{err: itemErr(0, issueops.ItemDepAdd, "", "bd-1",
|
|
&issueops.DependencyHierarchyConflictError{IssueID: "bd-1", BlockerID: "bd-2", BlockerIsAncestor: false})}
|
|
plain := &roleBatchApplier{err: itemErr(0, issueops.ItemDepAdd, "", "bd-1", issueops.ErrDependencyCycle)}
|
|
body := `{"actor":"alice","items":[{"kind":"create","create":{"title":"one"}}]}`
|
|
|
|
hierarchyBody := decodeBody(t, newApplyBatchServer(t, hierarchy).claim(t, batchApplyPath, body))
|
|
if hierarchyBody["issue_id"] != "bd-1" || hierarchyBody["blocker_id"] != "bd-2" {
|
|
t.Errorf("hierarchy refusal = %v, want issue_id and blocker_id from the refusing transaction", hierarchyBody)
|
|
}
|
|
if hierarchyBody["blocker_is_ancestor"] != false {
|
|
t.Error("blocker_is_ancestor is not emitted when false; both polarities are reported")
|
|
}
|
|
|
|
plainBody := decodeBody(t, newApplyBatchServer(t, plain).claim(t, batchApplyPath, body))
|
|
for _, member := range []string{"issue_id", "blocker_id", "blocker_is_ancestor"} {
|
|
if _, present := plainBody[member]; present {
|
|
t.Errorf("the plain cycle refusal carries %s; their ABSENCE is what tells the two refusals apart", member)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestApplyBatchMetadataMembersDecodeAPresentNull is the pin on the GENERATED
|
|
// CLIENT, and it is the only test here that decodes rather than asserting on
|
|
// wire bytes — because the bug it exists to prevent is invisible at the wire.
|
|
//
|
|
// A metadata member declared as *json.RawMessage cannot READ a present null:
|
|
// encoding/json answers a JSON null against a pointer by setting the pointer to
|
|
// nil, before any UnmarshalJSON runs, so a member holding `null` and a member
|
|
// that was never sent decode to the same value. On the metadata plane those
|
|
// mean opposite things — the key holds null, versus the key is absent.
|
|
//
|
|
// The schema's x-go-type-skip-optional-pointer is what makes the member a bare
|
|
// json.RawMessage, which is an Unmarshaler and receives the literal. This test
|
|
// is what keeps the next `make api-gen` from regenerating that away.
|
|
func TestApplyBatchMetadataMembersDecodeAPresentNull(t *testing.T) {
|
|
for _, test := range []struct {
|
|
name string
|
|
body string
|
|
want *string
|
|
}{
|
|
{"a present null is the literal", `{"replace":null}`, applyStrPtr("null")},
|
|
{"an omitted member is nil", `{}`, nil},
|
|
{"an ordinary value round-trips", `{"replace":{"a":1}}`, applyStrPtr(`{"a":1}`)},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
var patch apigen.ApplyMetadataPatch
|
|
if err := json.Unmarshal([]byte(test.body), &patch); err != nil {
|
|
t.Fatalf("decoding %s: %v", test.body, err)
|
|
}
|
|
switch {
|
|
case test.want == nil && patch.Replace != nil:
|
|
t.Fatalf("Replace = %s, want nil: an omitted member never asked for a write", string(patch.Replace))
|
|
case test.want != nil && patch.Replace == nil:
|
|
t.Fatalf("Replace = nil, want %s: a present null is a VALUE, and a client that cannot tell "+
|
|
"it from an absent member cannot express a null-valued document", *test.want)
|
|
case test.want != nil && string(patch.Replace) != *test.want:
|
|
t.Fatalf("Replace = %s, want %s", string(patch.Replace), *test.want)
|
|
}
|
|
})
|
|
}
|
|
|
|
// The create item's own metadata member carries the same shape for the same
|
|
// reason, and a pointer there would silently drop a caller's `null`.
|
|
var create apigen.ApplyCreateItem
|
|
if err := json.Unmarshal([]byte(`{"title":"t","metadata":null}`), &create); err != nil {
|
|
t.Fatalf("decoding a create item: %v", err)
|
|
}
|
|
if string(create.Metadata) != "null" {
|
|
t.Fatalf("ApplyCreateItem.Metadata = %s, want the literal null", string(create.Metadata))
|
|
}
|
|
}
|
|
|
|
func applyStrPtr(s string) *string { return &s }
|