* feat(serve): serve a registered backend from the store bd already opened
`bd serve` was the one command that did not use bd's own store-creation
path. Ordinary CLI commands dispatch the workspace open through
`backends.Lookup` (cmd/bd/store_factory.go, and PersistentPreRunE inlines
the same arm), so `bd list` and `bd create` already work on any registered
backend. `runServe` instead built a unit-of-work provider of its own,
hard-wired to Dolt's SQL wire — and `serveModeGate` classified a registered
workspace as EMBEDDED and refused it before construction even started.
Serve now creates nothing. On the registered arm it takes
`httpapi.Config.Reader` and `Config.Claimer` off the store PersistentPreRunE
already opened, so there is one creation path rather than two: a second
handle would double the pools and self-conflict with any backend holding an
exclusive workspace lock. The store's lifecycle stays where it was —
PersistentPostRunE closes it, after runServe returns and therefore after the
server has drained.
The roles come from BENEATH the hook decorator (one `HookFiringStore.Unwrap`,
never `storage.UnwrapStore`, which would drop the telemetry layer too). A
store's accessors hand out its decorators by design, so the obvious
`store.IssueClaimer()` returns a claimer that runs the workspace's on_update
script for every claim it lands — exactly what this server documents it does
not do. `httpapi.Listen` refuses a hook-firing role, so getting this wrong is
a startup error rather than a silent subprocess per claim.
`serveModeGate` becomes `serveDatabaseSource`: one function that is both the
gate and the wiring decision, so the two cannot disagree about one workspace.
It consults the registry BEFORE any Dolt-mode signal, matching the order the
store open already resolves them in — a registered workspace opens its
registered store even with BEADS_DOLT_SHARED_SERVER=1 exported, and resolving
it the other way here would build a Dolt provider over a non-Dolt store. That
ordering also closes a latent CGO_ENABLED=0 bug: `isEmbeddedMode` is a
constant false there, so the old gate ADMITTED a registered workspace and
handed it to `resolveServerModeUOWTopology`, which either failed with a
misleading Dolt error or connected to a defaulted host and served the wrong
database.
The embedded-Dolt refusal is unchanged and unweakened: same typed
`ErrUnsupported{Op: "serve", Backend: "embedded-dolt"}`, same message, same
permanence — its commit protocol runs outside the SQL transaction, so this
server's per-request atomicity would be a lie there.
The classification now runs after `GetContextInfo`, because it reads the
workspace's configuration. A directory with no workspace at all therefore
reports that rather than reporting the embedded refusal for a workspace
nobody found.
TestServeBuildsOnlyAProviderBackedServer pinned the world this replaces and
could not be satisfied, only rewritten.
TestServeNamesOneDatabaseSourcePerServerItBuilds keeps the property it
actually protected: every httpapi.Config in cmd/bd names exactly one complete
database source, both arms exist, and a roles-backed one is built only inside
a function that consults serveDatabaseSource.
Agent-Signature: claude-opus-5
Co-authored-by: CI Bot <ci@beads.test>
* fix(serve): make the registered-backend arm honest about itself
Four findings, three of them things this arm asserted and one it never
proved.
THE IDENTITY HANDSHAKE LIED. GET /v0/beads/context reported
backend="dolt", dolt_mode="embedded", database="beads" for a registered
workspace — a confident description of the exact topology bd serve
refuses to serve, on the one endpoint automation is told to trust for a
server's identity, while the startup line beside it named the registered
backend correctly. The cause was the shared projection: it hardcoded the
backend to "dolt" and copied the Dolt fields unconditionally, and both of
those DEFAULT rather than fail. The fix is in that projection rather
than in runServe, because `bd context`, `bd context --json` and this
endpoint all read identity through domain.PublishedContext so they cannot
name one workspace differently; correcting the value in serve would have
made HTTP truthful and left the CLI printing `backend: dolt` in the same
directory. There were TWO copies of the hardcode — the contextinfo use
case and `bd context`'s direct route — so the policy is now one method,
domain.ContextInfo.SetBackendIdentity, that both call, and a test
compares what the two routes publish for one workspace. A registered
backend reports the EMPTY string for dolt_mode and database: bd does not
implement the backend and cannot know which database its Open settled on,
so any non-empty value is the same lie made quieter. No wire field is
renamed, retyped or dropped; both stay required strings and the v0 shape
is unchanged, spec and generated types untouched.
THE ARM'S CORE PROPERTY IS NOW PINNED. Nothing distinguished "serve
answers from the store bd already opened" from "serve opens a second
store": same reads, same claims, same handshake, same clean shutdown, and
replacing `store` with a self-opened handle compiled and passed
everything. Two assertions close it. The registry now hands back stores
whose readers answer with an issue named after the open that produced
them, so GET /v0/beads/ready says WHICH store the server is on; and the
end-to-end test counts opens through the registry and requires exactly
one for the process, which catches the leak the substitution leaves
behind. The stated mutant fails both.
`bd --readonly serve` IS REFUSED. It had degraded differently and
silently on each source: on the store source the root command opens
through backend.OpenReadOnly and serve took its claimer off that store,
so the server bound, went on advertising `issues.claim` — the capability
set comes off the route table and cannot see a CLI flag — and answered
every claim 500 with the issue left open; on the provider source serve
builds its own writable provider, so the flag bought nothing and every
claim landed. The gate runs before the workspace is resolved, so the
answer cannot depend on the topology. Narrowing the advertised capability
set instead was rejected as a wire change: `capabilities` is the
documented pre-flight a client checks, and making an operation's presence
depend on a flag on the process that started the server gives a client
something it cannot discover before connecting. Refusing is also what bd
already does one layer down for a backend that cannot guarantee
mutation-free access.
Agent-Signature: claude-opus-5
Co-authored-by: CI Bot <ci@beads.test>
* docs(serve): label the readonly refusal as breaking, and stop over-claiming
Three corrections from the verification pass, none of them code-behavior:
CHANGELOG: the --readonly serve refusal was filed under Fixed. On a Dolt
SQL-server workspace it is a BREAK, not a fix: the flag was a silent no-op
there and the server bound fully writable, so anyone scripting
`bd --readonly serve` as a "safe" read server loses it on upgrade. Moved to
Changed, marked BREAKING, and it now says what to do instead.
bd context: mode/database are Dolt-only now, and printing bare labels with
nothing after them reads on a terminal as though bd failed to determine them
rather than as though they do not apply. Omitted when empty, like every other
optional field in that block.
context_identity_test.go: the parity test's comment claimed it compares what
both `bd context` routes publish. It does not — it rebuilds the snapshot and
calls applyContextBackend directly, so it pins the shared projection, not
contextCmd's own wiring. Recorded as an explicit NOT COVERED note rather than
left to read as more coverage than exists.
Also worth recording: the lint check reported earlier was near-vacuous.
`golangci-lint --new-from-rev=HEAD` on a committed clean tree diffs against
itself. Re-run against the real merge base it is genuinely 0 issues.
Agent-Signature: claude-opus-5
Co-authored-by: CI Bot <ci@beads.test>
---------
Co-authored-by: CI Bot <ci@beads.test>
153 lines
4.9 KiB
Go
153 lines
4.9 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"os"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/spf13/pflag"
|
|
)
|
|
|
|
// Shared plumbing for the tests that run `bd serve` IN-PROCESS.
|
|
//
|
|
// In-process is not a convenience here: a registered backend is init-time Go
|
|
// wiring and OSS registers none, so a spawned `bd` has nothing to register and
|
|
// could not reach that arm at all. What that costs is a bound server and a set
|
|
// of package globals inside the test binary every other test shares, which is
|
|
// what the snapshot-and-restore below exists for.
|
|
//
|
|
// None of it is cgo-specific, so it lives outside the embedded-Dolt end-to-end
|
|
// file that first needed it.
|
|
|
|
// restoreServeGlobals snapshots the package state one in-process serve run can
|
|
// touch and puts it back afterwards, so a registered backend and a bound server
|
|
// cannot leak into the tests sharing this binary.
|
|
//
|
|
// The flag set is part of that state and the least obvious part of it: cobra
|
|
// merges every inherited persistent flag into serveCmd's own FlagSet the first
|
|
// time it parses one, so a run through rootCmd.Execute leaves `bd serve`
|
|
// carrying --json, --db and the rest of the root's surface. That is what
|
|
// TestServeFlags reads. ResetFlags plus the command's own registration function
|
|
// is the un-merge cobra does not offer.
|
|
func restoreServeGlobals(t *testing.T) {
|
|
t.Helper()
|
|
origStore, origDBPath := store, dbPath
|
|
origServer, origProxied := serverMode, proxiedServerMode
|
|
origAddr, origNonLoopback := serveAddr, serveAllowNonLoopback
|
|
origCtx, origCancel := rootCtx, rootCancel
|
|
origCmdCtx, origUseGlobals := cmdCtx, testModeUseGlobals
|
|
t.Cleanup(func() {
|
|
if store != nil && store != origStore {
|
|
store.Close()
|
|
}
|
|
serveCmd.ResetFlags()
|
|
registerServeFlags(serveCmd) // rebinds serveAddr/serveAllowNonLoopback to the defaults
|
|
store, dbPath = origStore, origDBPath
|
|
serverMode, proxiedServerMode = origServer, origProxied
|
|
serveAddr, serveAllowNonLoopback = origAddr, origNonLoopback
|
|
rootCtx, rootCancel = origCtx, origCancel
|
|
cmdCtx, testModeUseGlobals = origCmdCtx, origUseGlobals
|
|
rootCmd.SetArgs(nil)
|
|
})
|
|
}
|
|
|
|
// resetRootPersistentFlags puts every root persistent flag back to the default
|
|
// it was declared with, and clears its Changed bit, for the duration of one
|
|
// test.
|
|
//
|
|
// A test binary that runs the root command in-process inherits whatever the
|
|
// thousands of tests before it left in those flags and their bound globals —
|
|
// and `Changed` is what several PersistentPreRunE branches dispatch on, not the
|
|
// value. A stale `--db`/`--database` alone makes the pre-run refuse with
|
|
// "--database ... is only supported in proxied-server mode" before the command
|
|
// under test ever runs. Reset before, restore after, so this test neither reads
|
|
// nor writes that shared state.
|
|
func resetRootPersistentFlags(t *testing.T) {
|
|
t.Helper()
|
|
type flagState struct {
|
|
value string
|
|
changed bool
|
|
}
|
|
before := map[string]flagState{}
|
|
rootCmd.PersistentFlags().VisitAll(func(f *pflag.Flag) {
|
|
before[f.Name] = flagState{value: f.Value.String(), changed: f.Changed}
|
|
if err := f.Value.Set(f.DefValue); err != nil {
|
|
t.Fatalf("reset --%s to its default %q: %v", f.Name, f.DefValue, err)
|
|
}
|
|
f.Changed = false
|
|
})
|
|
t.Cleanup(func() {
|
|
rootCmd.PersistentFlags().VisitAll(func(f *pflag.Flag) {
|
|
state, ok := before[f.Name]
|
|
if !ok {
|
|
return
|
|
}
|
|
_ = f.Value.Set(state.value)
|
|
f.Changed = state.changed
|
|
})
|
|
})
|
|
}
|
|
|
|
// captureStdoutLines redirects os.Stdout and streams its lines. bd serve prints
|
|
// the address it bound — the only way to discover an ephemeral port — to
|
|
// stdout, and the server is running by the time it does.
|
|
func captureStdoutLines(t *testing.T) (<-chan string, func()) {
|
|
t.Helper()
|
|
r, w, err := os.Pipe()
|
|
if err != nil {
|
|
t.Fatalf("os.Pipe: %v", err)
|
|
}
|
|
orig := os.Stdout
|
|
os.Stdout = w
|
|
|
|
lines := make(chan string, 64)
|
|
go func() {
|
|
defer close(lines)
|
|
scanner := bufio.NewScanner(r)
|
|
for scanner.Scan() {
|
|
lines <- scanner.Text()
|
|
}
|
|
}()
|
|
|
|
var stopped bool
|
|
stop := func() {
|
|
if stopped {
|
|
return
|
|
}
|
|
stopped = true
|
|
os.Stdout = orig
|
|
_ = w.Close()
|
|
}
|
|
t.Cleanup(func() {
|
|
stop()
|
|
_ = r.Close()
|
|
})
|
|
return lines, stop
|
|
}
|
|
|
|
// waitForBoundAddress reads the address `bd serve` printed on stdout, which is
|
|
// the only way to discover the port under the ephemeral default. The server is
|
|
// already accepting by the time that line is written.
|
|
//
|
|
// done carries the run's result so a serve that failed before binding is
|
|
// reported as its own error rather than as a two-minute timeout.
|
|
func waitForBoundAddress(t *testing.T, lines <-chan string, done <-chan error) string {
|
|
t.Helper()
|
|
deadline := time.After(2 * time.Minute)
|
|
for {
|
|
select {
|
|
case line, ok := <-lines:
|
|
if !ok {
|
|
t.Fatalf("bd serve exited before it bound: %v", <-done)
|
|
}
|
|
const prefix = "bd serve: listening on http://"
|
|
if addr, found := strings.CutPrefix(strings.TrimSpace(line), prefix); found {
|
|
return addr
|
|
}
|
|
case <-deadline:
|
|
t.Fatal("bd serve did not print a bound address")
|
|
}
|
|
}
|
|
}
|