beads/cmd/bd/proxy_capability.go
Julian Knutsen 24a9da6cc7
test(proxy): topology-parameterized history and remote front-door matrix (#6269)
* feat(ga-p9iuv.22): add shared tracker proxy storage seam

* fix(ga-p9iuv.22): preserve tracker storage capabilities safely

* test(ga-p9iuv.22): cover tracker adapter label semantics

* test(ga-p9iuv.22): harden tracker adapter contracts

* fix(ga-p9iuv.22): reject invalid proxied tracker stores

* feat(ga-p9iuv.1): route Linear and Jira front doors through proxy store

* test(ga-p9iuv.1): exercise tracker mutations through UOW store

* fix(ga-p9iuv.1): preserve proxied Linear endpoint config

* test(ga-p9iuv.1): cover proxied Linear endpoint and direct config

* feat(ga-p9iuv.19): add typed proxied capability matrix

* feat(proxy): enforce typed capability matrix before provider

* test(proxy): cover command capability rows and claim caps

* test(proxy): check capability rows across topologies

* fix(proxy): validate capabilities before workspace side effects

* fix(proxy): refuse ready claim max rows caps

* feat(proxy): add shared maintenance capability policy

* fix(proxy): key maintenance refusals by command path

* test(proxy): cover nested maintenance refusals

* fix(proxy): enumerate nested maintenance command paths

* fix(proxy): refine compact and nested maintenance policy

* test(proxy): prove maintenance refusals preserve files

* fix(proxy): cover admin and remote maintenance refusals

* fix(proxy): refuse doctor before store initialization

* test(proxy): define history capability command matrix

* fix(proxy): wire history capability refusals to front door

* fix(proxy): refuse top-level sync history path

* fix(proxy): preserve maintenance refusal codes

* feat(proxy): classify history as supported UOW API

* feat(proxy): classify transform capability paths

* test(proxy): harden transform capability matrix

* fix(proxy): drive transform validation from exact rows

* fix(proxy): drive transform matrix from normalized flags

* fix(proxy): bound external backend dials per attempt

* test(proxy): cover bounded blocked backend dial

* fix(proxy): make transform capability policy row-driven

* fix(proxy): make transform capability policy row-driven

* fix(proxy): classify formula swarm and merge-slot refusals

* test(proxy): enforce workflow refusal contract

* fix(proxy): classify Dolt remote history boundaries

* test(proxy): enforce history refusal contract

* test(proxy): cover canceled backend dial cleanup

* test(proxy): cover real TCP blackhole cancellation

* test(proxy): cover external transport lifecycle matrix

* test(proxy): assert stable dial failure diagnostics

* test(proxy): add outage reconnect acceptance matrix

* test(proxy): make unix outage bridge restartable

* test(proxy): bound outage subprocess cleanup

* test(proxy): cover upstream restart with retained endpoint bridge

* test(proxy): stabilize managed-local outage contract

* fix(proxy): retire managed proxy when backend exits

* test(proxy): accept managed child retirement restart

* test(proxy): cover workflow refusals at bd front door

* test(proxy): cover history VC front doors

* test(proxy): pass valid workflow refusal arguments

* test(proxy): assert text and json refusal contracts

* test(proxy): assert exact workflow refusal codes

* test(proxy): guard refusal issue-row stability

* fix(proxy): expose non-mutating capability refusals

* test(proxy): match stable refusal text

* test(proxy): compare refusal artifact snapshots

* test(proxy): assert exact refusal messages

* test(proxy): retain direct workflow behavior

* test(proxy): match nested refusal messages

* test(proxy): cover direct-only front-door refusals

* test(proxy): provide valid direct-only command args

* fix(migrate): repair missing proxied sidecar on reentry

* fix: checkpoint Dolt mode migrations for safe retry

* fix: harden migration journal topology and retries

* fix: fsync migration journal removal

* fix: fail on migration journal directory sync errors

* fix: reject external ownership in every migration phase

* fix: enforce canonical shared migration topology

* fix: enforce live migration topology

* test: add migration front-door and topology regressions

* fix: require physical Dolt roots for migration

* test: strengthen migration front-door contracts

* fix: reject missing or invalid Dolt migration roots

* fix: keep shared migration dry-runs side-effect free

* fix: require Dolt repository identity for migrations

* fix: validate Dolt repository identity metadata

* fix: require typed Dolt repo state identity

* test: expand migration front-door CRUD assertions

* test: make migration JSON dry-run front-door safe

* test: sanitize Dolt environment for migration front door

* test: use cgo binary for migration front door

* test: omit empty Dolt overrides in migration front door

* test: isolate migration front door from test mode

* test: isolate home for migration front door

* test: stop supervised Dolt before reverse migration

* fix: reject empty Dolt head refs

* test: harden migration topology invariants

* test: harden external and shared topology refusals

* test: snapshot migration refusal artifacts

* test: cover external migration refusal phases

* fix: refuse stale proxied sidecars during migration

* test: strengthen migration artifact and external front door checks

* feat: type external migration refusals

* test: assert external refusal starts no proxy

* fix: validate migration journal sidecar topology

* fix: make sidecar recovery phase aware

* fix: honor persisted shared topology during migration

* test: exercise external journal migration front door matrix

* test(tracker): add shared conformance harness

* test: harden external migration matrix fixtures

* test: preserve durable dolt gate lock in matrix

* test: preseed gate lock for refusal matrix

* test: cover malformed migration state front door

* fix: type malformed migration config refusals

* fix: type migration preflight state errors

* test: separate migration JSON stdout from warnings

* test: reach typed malformed journal refusal

* test: assert migration retry phase and idempotence

* test: cover shared migration checkpoint retries

* fix: make reverse migration idempotent without sidecar

* test: cover proxied to shared retries

* fix: derive shared topology from persisted YAML

* fix: validate shared migration no-op state

* fix: allow completed proxied shared no-op

* fix: validate forward proxied no-op sidecar

* test: reject bad already-proxied sidecars

* fix: reject stale proxy controls on no-op

* fix: fail closed on malformed migration workspace yaml

* test: pin migration yaml topology precedence

* Cover forward migration no-op ownership refusals (ga-p9iuv.26.5.2)

Agent-Signature: unknown-model/unknown-reasoning

* Strengthen migration retry sentinel coverage (ga-p9iuv.26.1)

Agent-Signature: unknown-model/unknown-reasoning

* Expand migration fault retry artifact coverage (ga-p9iuv.26.1)

Agent-Signature: unknown-model/unknown-reasoning

* Add reverse migration frontdoor fault matrix (ga-p9iuv.26.1.1)

Agent-Signature: unknown-model/unknown-reasoning

* test: cover shared migration frontdoor fault matrices

* test: strengthen direct migration matrix assertions

* test: preserve migration dependency edges

* test: assert exact migration dependency edges

* test: parse migration dependency edges from batch list

* test: fix shared migration matrix compile

* test: verify shared dependencies before shutdown

* test(proxy): cover history remote front-door topology matrix

* docs: define direct-local ownership handoff contract

* fix(ci): repair pre-review CI failures on proxy parity branch

Five PR-introduced failures across the docs, PR Core, and Proxied Dolt Cmd
lanes. Each fix is scoped to the evidenced defect.

- test/docsync: TestEveryDocsPageIsPublished flagged
  docs/architecture/ownership-handoff-contract.md as unpublished. It is an
  internal Beads/Gas City handoff contract with no Mintlify frontmatter and
  no inbound links, so move it to engdocs/design/ beside its peers rather
  than publishing it.

- cmd/bd: TestProxyWorkflowRefusalContractAndNoMutation asserted on
  commandDidWrite, a process-wide atomic latch set by 71 non-test sites and
  never reset, so it reported an earlier test's write. Baseline and restore
  it around the assertion, matching the save/reset/restore idiom already
  used in proxied_lookup_failure_test.go and readonly_policy_test.go.

- cmd/bd: the new pre-provider gate short-circuited compact.go's refusal
  with new wording, breaking TestProxiedServerCompactDolt/non_dolt_mode_-
  rejected in an unchanged test. Restore the long-standing message; the
  proxy.compact.unsupported code is unchanged.

- internal/storage/dbproxy/proxy: the unix subtests bound sockets under
  t.TempDir(), whose embedded test name overflows macOS's ~104-byte
  sun_path limit ("bind: invalid argument"). Add unixSocketPath() to place
  them in a short temp dir.

- cmd/bd: migration topology compared recorded and canonical Dolt roots
  lexically, so macOS's /var -> /private/var symlink made equivalent paths
  compare unequal. Add sameMigrationRoot(), mirroring the existing
  resolveExistingPrefix idiom in cmd/bd/doctor/git.go.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(review): address blocker and major findings from adopt-pr review

Maintainer review fixup for the proxy parity branch, iterations 1-2.
Blockers and majors from the review synthesis and quality scorecard.

Blockers:

- cmd/bd/migrate_dolt_mode.go: resuming from migratePrepared rebuilt the
  migration plan from the current argv instead of replaying the recorded
  one. A resume that omitted or changed --idle-timeout wrote a sidecar the
  target_configured check then rejected, and because that check runs only
  after the phase advances past migratePrepared, the block never ran again
  — the workspace stayed wedged in proxied-server mode with no in-tool
  recovery. Replay j.Sidecar and warn when the supplied value is ignored.

- internal/tracker/store.go: NewStore double-wrapped already-adapted values.
  directStore embeds the storage.Storage interface, so *directStore also
  satisfies storage.Storage and was re-wrapped as
  &directStore{Storage: &directStore{...}}; the inner value can never
  satisfy storage.IssueLifecycleStore, which silently degraded
  ApplyIssueUpdate to a bare UpdateIssue — no labels, no lifecycle
  transaction. Match the tracker's own adapters by concrete type first.
  Testing value.(Store) first, as the review suggested, does not work:
  storage.Storage is a strict superset of Store, so a raw direct store
  satisfies Store too and would be returned un-adapted, relocating the same
  bug. The branch order is documented at the call site.

Majors:

- internal/tracker/store.go: directStore.ApplyIssueUpdate now calls
  syncIssueLabels, which normalizes both label sets (trim, drop empty) and
  restores the semantics the pull path had before this seam moved behind
  ApplyIssueUpdate. The un-normalized local copy churned remove+add on
  whitespace-only differences and let an empty label reach AddLabel; it is
  deleted rather than left as a second, divergent implementation.

- Both regressions were invisible to the suite. Adds
  TestNewEngineKeepsDirectStoreAdaptationIntact, TestNewStoreIsIdempotent,
  TestDirectStoreApplyIssueUpdateNormalizesLabels, and
  TestMigrateToProxiedServer_ResumeReplaysRecordedIdleTimeout (changed /
  omitted / never subtests, each also asserting the reverse-migration escape
  hatch still recovers). All four were verified to fail against the
  pre-fix production code with the predicted symptoms.

Non-gating follow-ups from the scorecard, fixed while nearby:

- cmd/bd/proxy_capability.go: treat ProxyOutcomeNA as "this command has no
  such flag" rather than a refusal, so an assert on an N/A row cannot return
  a non-nil error carrying an empty message.

- cmd/bd/errors.go: emit the rule's real Mutates value in the JSON refusal
  envelope instead of a hardcoded false.

- cmd/bd/main.go: the doctor pre-provider check returned unconditionally,
  so a nil result (every doctor subcommand) skipped the legacy-store guard
  and autocommit-mode resolution that other skipsStoreInit commands run.
  Return only on a real refusal.

- internal/tracker/engine.go: type NewEngine's store parameter as Store so
  the seam names its contract, and drop the now-dead applyPullIssueUpdate.

- CHANGELOG.md: record the proxied `bd ready --claim` row-cap refusal, which
  was a behavior change shipped without a release note.

Iteration 2 -- gating major (uowStore/directStore external_ref divergence):

- internal/tracker/uow_store.go: GetIssueByExternalRef resolved through a
  single merged search over both storage planes, which has no plane
  preference: it is a UNION ALL ordered by content and terminating in
  `id ASC`, so one external_ref present on both planes resolved to whichever
  row's id sorted first. The direct backend is explicitly issues-first --
  issueops.GetIssueByExternalRefInTx queries `issues` and falls through to
  `wisps` only on sql.ErrNoRows, and says why ("so that pushed ephemeral
  beads are found during pull dedup"). The consumer is the pull dedup, which
  updates whatever row comes back, so the divergence was a silent write to
  the wrong local bead under --proxied-server only. Query the issues plane
  first via SkipWisps, then fall back.

  The fallback is the merged search rather than the review's literal
  Ephemeral=true: that filter contributes an `ephemeral = 1` predicate the
  direct backend's `SELECT id FROM wisps WHERE external_ref = ?` does not
  have, and wisp-plane rows legitimately carry ephemeral=0 (NoHistory beads;
  see types.IssueFilter.EphemeralTier). Taking it literally would have traded
  one divergence for a narrower one. Verified: implementing the prescription
  fails the ephemeral_flag_clear subtest below.

- internal/tracker/uow_store_engine_test.go: the engine fake now models plane
  routing (SkipWisps / Ephemeral / merged) instead of one flat map, so the
  contract is expressible at all. Adds
  TestUOWStoreGetIssueByExternalRefPrefersIssuePlane, whose wisp id sorts
  first so "first merged hit" fails it, and
  TestUOWStoreGetIssueByExternalRefFallsBackToWispPlane over both ephemeral
  values. Verified to fail against the pre-fix uow_store.go.

- internal/tracker/conformance: the shared suite gains a Wisps plane and
  external_ref_resolution_prefers_issue_plane, so this is a contract both
  backends are held to rather than one adapter's unit test.

Iteration 2 -- non-gating follow-ups from the scorecard:

- cmd/bd/migrate_dolt_mode.go: scope the migratePrepared sidecar-equivalence
  check in runMigrateFromProxiedServer to reverse journals. A forward journal
  at that phase records the sidecar it is about to write, so a crash in the
  pre-write window leaves none on disk -- the correct state -- and the
  unscoped check refused the documented escape hatch by naming a missing
  file, stranding the workspace. Tested against TargetMode's forward value so
  the guard stays live for both reverse targets, "server" and
  "shared-server". Adds
  TestMigrateFromProxiedServer_ForwardJournalAtPreparedIsNotSidecarRefused,
  verified to fail against the unscoped guard.

- cmd/bd/linear.go: buildLinearClientAPIOnly returned the OAuth client inline
  and never reached the WithEndpoint block, so a configured
  linear.api_endpoint was honored for an API key and ignored for OAuth. Hoist
  the endpoint application after the branch, as Tracker.Init does, and add
  the OAuth mirror of the existing endpoint test.

- cmd/bd/ready_max_rows_proxied_test.go: pin the proxied --max-rows refusal
  on `bd ready --claim`. It lives in RunE above the dispatch and nothing
  below it can enforce a cap, but the existing coverage all sits below it.
  Covers both cap sources (--max-rows and BEADS_MAX_ROWS) and the negative
  case that the refusal is conditioned on a live cap, not on --claim.

- engdocs/design/ownership-handoff-contract.md: trim the trailing blank line
  at EOF flagged by `git diff --check`.

Iteration 3 -- non-gating residual on the iteration-2 fix:

- internal/tracker/uow_store.go: the issues-first fix above split one logical
  lookup across two read transactions. uow.RunTxRead opens a fresh unit of
  work per call, so calling s.SearchIssues twice left the wisp fallback's
  premise -- "the issues plane is already known empty" -- without a shared
  snapshot: a concurrent same-ref insert into the issues plane landing between
  the two reads could let the merged fallback return the wisp, re-creating the
  wrong-row write that ordering exists to prevent. The consumer is the pull
  dedup loop, so it runs per imported issue. Both plane reads now share a
  single RunTxRead, which is also the shape the direct backend uses (both
  planes inside one withReadTx). Plane ordering is unchanged.

- internal/tracker/uow_store_engine_test.go: the engine fake counts the units
  of work it hands out, and
  TestUOWStoreGetIssueByExternalRefUsesOneReadTransaction pins that count at 1
  across the two paths that actually perform both reads -- the wisp fallback
  and the miss. An issues-plane hit short-circuits after one read and would
  pass either way, so it is not a case. Verified to fail against the
  two-transaction version with "opened 2, want 1".

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-05 08:25:49 -07:00

361 lines
17 KiB
Go

package main
import (
"fmt"
"strings"
"github.com/spf13/cobra"
)
// ProxyCapability identifies a command feature whose availability differs by
// storage topology.
type ProxyCapability string
const (
ProxyCapReadonly ProxyCapability = "readonly"
ProxyCapMaxRows ProxyCapability = "max-rows"
ProxyCapWatch ProxyCapability = "watch"
ProxyCapRepo ProxyCapability = "repo"
)
// ProxyMode identifies the selected storage topology.
type ProxyMode string
const (
ProxyModeDirect ProxyMode = "direct"
ProxyModeProxied ProxyMode = "proxied-server"
)
// ProxyTopology distinguishes the provider deployment shape. Capability
// policy is currently identical across proxied shapes, but retaining this
// dimension prevents an external TCP server from being conflated with a local
// managed one as more surfaces are added.
type ProxyTopology string
const (
ProxyTopologyAny ProxyTopology = "any"
ProxyTopologyManagedLocal ProxyTopology = "managed-local"
ProxyTopologyExternalTCP ProxyTopology = "external-tcp"
ProxyTopologyExternalUnix ProxyTopology = "external-unix"
)
// ProxyCapabilityOutcome describes what the front door does with a feature.
type ProxyCapabilityOutcome string
const (
ProxyOutcomeHonored ProxyCapabilityOutcome = "honored"
ProxyOutcomeRefused ProxyCapabilityOutcome = "refused"
ProxyOutcomeDelegated ProxyCapabilityOutcome = "delegated"
ProxyOutcomeNA ProxyCapabilityOutcome = "N/A"
)
// proxyCapabilityRule is the stable contract for one command/argument/topology
// capability. Mutates is false for all refusals; ExitCode is used by the CLI
// when rendering a typed refusal.
type proxyCapabilityRule struct {
Outcome ProxyCapabilityOutcome
Code string
Message string
ExitCode int
Mutates bool
}
// ProxyCapabilityError is a machine-identifiable front-door refusal.
type ProxyCapabilityError struct {
Code string
Message string
ExitCode int
Mutates bool
}
func (e *ProxyCapabilityError) Error() string { return e.Message }
func refused(code, message string) proxyCapabilityRule {
return proxyCapabilityRule{Outcome: ProxyOutcomeRefused, Code: code, Message: message, ExitCode: 1}
}
func honored() proxyCapabilityRule {
return proxyCapabilityRule{Outcome: ProxyOutcomeHonored, ExitCode: 0}
}
func notApplicable() proxyCapabilityRule { return proxyCapabilityRule{Outcome: ProxyOutcomeNA} }
// ProxyCapabilityKey identifies a command's flag/argument on a topology.
// Argument is intentionally explicit (for example, "--watch"), allowing
// callers and tests to distinguish a command that lacks a flag (N/A) from one
// that refuses it.
type ProxyCapabilityKey struct {
Command string
Argument string
Mode ProxyMode
Topology ProxyTopology
}
// ProxyCapabilityRow is an inspectable command/argument/topology policy row.
type ProxyCapabilityRow struct {
ProxyCapabilityKey
Rule proxyCapabilityRule
}
var proxyMaintenanceRefusals = map[string]proxyCapabilityRule{
"doctor": refused("proxy.doctor.unsupported", "doctor is not supported in proxied-server mode"),
"backup": refused("proxy.backup.unsupported", "backup is not supported in proxied-server mode"),
"restore": refused("proxy.restore.unsupported", "restore is not supported in proxied-server mode"),
"diff": refused("proxy.diff.unsupported", "diff is not supported in proxied-server mode"),
"flatten": refused("proxy.flatten.unsupported", "flatten is not supported in proxied-server mode"),
"migrate": refused("proxy.migrate.unsupported", "migrate is not supported in proxied-server mode"),
"migrate-personal": refused("proxy.migrate.unsupported", "migrate-personal is not supported in proxied-server mode"),
"branch": refused("proxy.branch.unsupported", "branch is not supported in proxied-server mode"),
"conflicts": refused("proxy.conflicts.unsupported", "conflicts is not supported in proxied-server mode"),
"vc": refused("proxy.vc.unsupported", "vc is not supported in proxied-server mode"),
"federation": refused("proxy.federation.unsupported", "federation is not supported in proxied-server mode"),
"repo": refused("proxy.repo.unsupported", "repo is not supported in proxied-server mode"),
// Wording matches the long-standing compact.go refusal this pre-provider
// gate now short-circuits, so the user-facing message does not change.
"compact": refused("proxy.compact.unsupported", "only 'compact --dolt' is supported in proxied-server mode"),
"backup init": refused("proxy.backup.unsupported", "backup init is not supported in proxied-server mode"),
"backup sync": refused("proxy.backup.unsupported", "backup sync is not supported in proxied-server mode"),
"backup remove": refused("proxy.backup.unsupported", "backup remove is not supported in proxied-server mode"),
"backup status": refused("proxy.backup.unsupported", "backup status is not supported in proxied-server mode"),
"backup restore": refused("proxy.backup.unsupported", "backup restore is not supported in proxied-server mode"),
"migrate sync": refused("proxy.migrate.unsupported", "migrate sync is not supported in proxied-server mode"),
"migrate-issues": refused("proxy.migrate.unsupported", "migrate-issues is not supported in proxied-server mode"),
"gate discover": refused("proxy.gate.unsupported", "gate discover is not supported in proxied-server mode"),
"admin cleanup": refused("proxy.admin.unsupported", "admin cleanup is not supported in proxied-server mode"),
"admin reset": refused("proxy.admin.unsupported", "admin reset is not supported in proxied-server mode"),
"dolt push": refused("proxy.dolt_push.unsupported", "dolt push is not supported in proxied-server mode"),
"dolt pull": refused("proxy.dolt_pull.unsupported", "dolt pull is not supported in proxied-server mode"),
"dolt commit": refused("proxy.dolt_commit.unsupported", "dolt commit is not supported in proxied-server mode"),
"dolt remote": refused("proxy.dolt_remote.unsupported", "dolt remote is not supported in proxied-server mode"),
"dolt remote add": refused("proxy.dolt_remote.unsupported", "dolt remote add is not supported in proxied-server mode"),
"dolt remote list": refused("proxy.dolt_remote.unsupported", "dolt remote list is not supported in proxied-server mode"),
"cook": refused("proxy.formula.unsupported", "cook is not supported in proxied-server mode"),
"ship": refused("proxy.formula.unsupported", "ship is not supported in proxied-server mode"),
"swarm create": refused("proxy.swarm.unsupported", "swarm create is not supported in proxied-server mode"),
"swarm list": refused("proxy.swarm.unsupported", "swarm list is not supported in proxied-server mode"),
"merge-slot create": refused("proxy.merge_slot.unsupported", "merge-slot create is not supported in proxied-server mode"),
"merge-slot check": refused("proxy.merge_slot.unsupported", "merge-slot check is not supported in proxied-server mode"),
"merge-slot acquire": refused("proxy.merge_slot.unsupported", "merge-slot acquire is not supported in proxied-server mode"),
"merge-slot release": refused("proxy.merge_slot.unsupported", "merge-slot release is not supported in proxied-server mode"),
"dolt remote reset-data": refused("proxy.dolt_remote.unsupported", "dolt remote reset-data is not supported in proxied-server mode"),
"sync": refused("proxy.sync.unsupported", "sync is not supported in proxied-server mode"),
}
func init() {
for parent, children := range map[string][]string{
"vc": {"merge", "commit", "status"},
"federation": {"sync", "status", "add-peer", "remove-peer", "list-peers"},
"repo": {"add", "remove", "list", "sync"},
"conflicts": {"list", "show", "resolve"},
"migrate": {"hooks", "issues"},
} {
rule := proxyMaintenanceRefusals[parent]
for _, child := range children {
path := parent + " " + child
proxyMaintenanceRefusals[path] = refused(rule.Code, path+" is not supported in proxied-server mode")
}
}
}
// validateProxyMaintenanceBeforeProvider rejects known direct-only commands
// before migrations, auto-start, or provider construction.
func validateProxyMaintenanceBeforeProvider(cmd *cobra.Command) error {
if cmd == nil {
return nil
}
name := cmd.Name()
path := strings.TrimSpace(strings.TrimPrefix(cmd.CommandPath(), cmd.Root().Name()))
if name == "compact" {
if cmd.Flags().Lookup("dolt") == nil {
return nil // root `bd compact` is the Dolt history command
}
dolt, _ := cmd.Flags().GetBool("dolt")
if dolt {
return nil
}
rule := proxyMaintenanceRefusals["compact"]
return HandleProxyCapabilityError(&ProxyCapabilityError{Code: rule.Code, Message: rule.Message, ExitCode: rule.ExitCode})
}
if rule, ok := proxyMaintenanceRefusals[path]; ok {
return HandleProxyCapabilityError(&ProxyCapabilityError{Code: rule.Code, Message: rule.Message, ExitCode: rule.ExitCode})
}
if class, ok := LookupHistoryCapability(path); ok && class == HistoryDirectOnly {
rule := refused("proxy.history.unsupported", path+" is not supported in proxied-server mode")
if specific, found := proxyMaintenanceRefusals[path]; found {
rule = specific
}
return HandleProxyCapabilityError(&ProxyCapabilityError{Code: rule.Code, Message: rule.Message, ExitCode: rule.ExitCode, Mutates: rule.Mutates})
}
if strings.Contains(path, " ") {
return nil
}
if rule, ok := proxyMaintenanceRefusals[name]; ok {
return HandleProxyCapabilityError(&ProxyCapabilityError{Code: rule.Code, Message: rule.Message, ExitCode: rule.ExitCode})
}
return nil
}
// LookupProxyCapabilityFor returns the command/argument-specific rule. An
// absent command row falls back to the topology-wide default.
func LookupProxyCapabilityFor(command, argument string, mode ProxyMode) (proxyCapabilityRule, bool) {
capability := ProxyCapability(argument)
if len(argument) > 2 && argument[:2] == "--" {
capability = ProxyCapability(argument[2:])
}
if commands, ok := proxyCommandCapabilities[command]; ok {
if modes, ok := commands[mode]; ok {
if rule, ok := modes[capability]; ok {
return rule, true
}
}
}
return LookupProxyCapability(mode, capability)
}
var proxyCapabilityMatrix = map[ProxyMode]map[ProxyCapability]proxyCapabilityRule{
ProxyModeDirect: {
ProxyCapReadonly: honored(), ProxyCapMaxRows: honored(),
ProxyCapWatch: honored(), ProxyCapRepo: honored(),
},
ProxyModeProxied: {
ProxyCapReadonly: refused("proxy.readonly.unsupported", "strict readonly is unavailable for dolt proxied-server backend; refusing to open a store that cannot guarantee mutation-free access"),
ProxyCapMaxRows: refused("proxy.max_rows.unsupported", "--max-rows / BEADS_MAX_ROWS is not supported in proxied-server mode"),
ProxyCapWatch: refused("proxy.watch.unsupported", "watch mode not supported in proxied-server mode"),
ProxyCapRepo: refused("proxy.repo.unsupported", "--repo is not supported with --proxied-server"),
},
}
var proxyCommandCapabilities = map[string]map[ProxyMode]map[ProxyCapability]proxyCapabilityRule{
"show": {ProxyModeProxied: {ProxyCapWatch: refused("proxy.watch.unsupported", "watch mode not supported in proxied-server mode")}},
"list": {ProxyModeProxied: {ProxyCapWatch: honored(), ProxyCapMaxRows: honored(), ProxyCapRepo: notApplicable()}},
"dep tree": {ProxyModeProxied: {ProxyCapMaxRows: honored()}},
"ready": {ProxyModeProxied: {ProxyCapMaxRows: refused("proxy.max_rows.unsupported", "--max-rows / BEADS_MAX_ROWS is not supported in proxied-server mode")}},
"graph": {ProxyModeProxied: {ProxyCapMaxRows: refused("proxy.max_rows.unsupported", "--max-rows / BEADS_MAX_ROWS is not supported in proxied-server mode")}},
"find-duplicates": {ProxyModeProxied: {ProxyCapMaxRows: refused("proxy.max_rows.unsupported", "--max-rows / BEADS_MAX_ROWS is not supported in proxied-server mode")}},
}
// proxyCapabilityRows materializes the policy for every supported proxied
// topology. Keeping rows explicit makes matrix audits and front-door tests
// deterministic even though the current provider implementations share rules.
var proxyCapabilityRows = buildProxyCapabilityRows()
func buildProxyCapabilityRows() []ProxyCapabilityRow {
topologies := []ProxyTopology{ProxyTopologyManagedLocal, ProxyTopologyExternalTCP, ProxyTopologyExternalUnix}
var rows []ProxyCapabilityRow
for _, topology := range topologies {
for _, capability := range []ProxyCapability{ProxyCapReadonly, ProxyCapMaxRows, ProxyCapWatch, ProxyCapRepo} {
rule, _ := LookupProxyCapability(ProxyModeProxied, capability)
rows = append(rows, ProxyCapabilityRow{ProxyCapabilityKey{"", string(capability), ProxyModeProxied, topology}, rule})
}
for command, modes := range proxyCommandCapabilities {
for mode, capabilities := range modes {
for capability, rule := range capabilities {
rows = append(rows, ProxyCapabilityRow{ProxyCapabilityKey{command, string(capability), mode, topology}, rule})
}
}
}
}
return rows
}
// LookupProxyCapabilityAt returns a topology-keyed rule. Unknown topology is
// rejected; ProxyTopologyAny applies the topology-independent direct policy.
func LookupProxyCapabilityAt(command, argument string, mode ProxyMode, topology ProxyTopology) (proxyCapabilityRule, bool) {
if topology != ProxyTopologyAny && topology != ProxyTopologyManagedLocal && topology != ProxyTopologyExternalTCP && topology != ProxyTopologyExternalUnix {
return proxyCapabilityRule{}, false
}
if len(argument) > 2 && argument[:2] == "--" {
argument = argument[2:]
}
for _, row := range proxyCapabilityRows {
if row.Command == command && row.Argument == argument && row.Mode == mode && row.Topology == topology {
return row.Rule, true
}
}
if topology == ProxyTopologyAny {
return LookupProxyCapabilityFor(command, argument, mode)
}
return proxyCapabilityRule{}, false
}
// LookupProxyCapability returns the typed rule for a mode/capability pair.
func LookupProxyCapability(mode ProxyMode, capability ProxyCapability) (proxyCapabilityRule, bool) {
rules, ok := proxyCapabilityMatrix[mode]
if !ok {
return proxyCapabilityRule{}, false
}
rule, ok := rules[capability]
return rule, ok
}
// AssertProxyCapability rejects unsupported features before provider setup.
func AssertProxyCapability(mode ProxyMode, capability ProxyCapability) error {
return AssertProxyCommandCapability("", mode, capability)
}
// AssertProxyCommandCapability checks a command-specific capability rule.
func AssertProxyCommandCapability(command string, mode ProxyMode, capability ProxyCapability) error {
if commands, ok := proxyCommandCapabilities[command]; ok {
if modes, ok := commands[mode]; ok {
if rule, ok := modes[capability]; ok {
// N/A means the command has no such flag, which is not a
// refusal. Without it, a future assert call site on an N/A row
// would return a non-nil error carrying an empty message.
if rule.Outcome == ProxyOutcomeHonored || rule.Outcome == ProxyOutcomeDelegated || rule.Outcome == ProxyOutcomeNA {
return nil
}
if rule.Code != "" {
return &ProxyCapabilityError{Code: rule.Code, Message: rule.Message, ExitCode: rule.ExitCode, Mutates: rule.Mutates}
}
return fmt.Errorf("%s", rule.Message)
}
}
}
rule, ok := LookupProxyCapability(mode, capability)
if !ok || (rule.Outcome != ProxyOutcomeHonored && rule.Outcome != ProxyOutcomeDelegated) {
if rule.Code != "" {
return &ProxyCapabilityError{Code: rule.Code, Message: rule.Message, ExitCode: rule.ExitCode, Mutates: rule.Mutates}
}
if rule.Message != "" {
return fmt.Errorf("%s", rule.Message)
}
return fmt.Errorf("%s is not supported in %s mode", capability, mode)
}
return nil
}
// validateProxyCapabilitiesBeforeProvider runs refusals that can be decided
// from argv before the proxied provider is opened.
func validateProxyCapabilitiesBeforeProvider(cmd *cobra.Command) error {
if cmd == nil {
return nil
}
name := cmd.Name()
if name == "create" && cmd.Flags().Changed("repo") {
return HandleProxyCapabilityError(AssertProxyCapability(ProxyModeProxied, ProxyCapRepo))
}
if name == "show" {
if watch, _ := cmd.Flags().GetBool("watch"); watch {
return HandleProxyCapabilityError(AssertProxyCommandCapability("show", ProxyModeProxied, ProxyCapWatch))
}
}
if name == "ready" {
maxRows, _, err := resolveMaxRows(cmd)
if err != nil {
return err
}
if maxRows > 0 {
return HandleProxyCapabilityError(AssertProxyCommandCapability(name, ProxyModeProxied, ProxyCapMaxRows))
}
}
if name == "graph" || name == "find-duplicates" {
maxRows, _, err := resolveMaxRows(cmd)
if err != nil {
return err
}
if maxRows > 0 {
return HandleProxyCapabilityError(AssertProxyCommandCapability(name, ProxyModeProxied, ProxyCapMaxRows))
}
}
return nil
}