beads/cmd/bd/proxied_server.go
Julian Knutsen b184dae412
fix(dbproxy): managed-local dolt readiness proves port ownership; recover onto a free port (#7184)
* fix(dbproxy): prove the managed dolt owns its port; move a taken Beads-chosen port

The managed-local backend's dolt port comes from a bind-and-close
(proxy.PickFreePort) when bd writes the generated config. The dolt
sql-server binds it only later, after the proxy child has run dolt
config and init and booted the server. If another process takes the port
in that gap, dolt logs "Port N already in use." and exits. But
DoltServer.waitReady only dialed the port, so it accepted the other
process's listener as ready. The proxy then published proxy.pid, its
backend health check saw dolt gone, and it shut down. bd init's first
ping got "unexpected EOF" and every retry after that got "connection
refused". Under parallel tests this hit any test that starts its own
managed backend.

Readiness now requires proof that the process Start launched owns the
port:
- DoltServer sends the child's stdout/stderr through a watcher that
  forwards to the server log. A dial counts only after dolt's own
  "Server ready. Accepting connections." line has appeared on that
  output. That line is info level, and every generated config uses
  info. A config with a quieter log_level has no such signal and keeps
  the dial-only check.
- A child that exits first is reported as the new server.ErrPortInUse
  when its output said its port was taken.

Recovery: DoltServer.SetPortRepicker lets Start move the config to a
fresh port, re-read it, and relaunch, up to 5 ports. dolt config/init
run only on the first attempt. bd's repicker,
repickManagedProxiedServerPort, needs to tell a port Beads chose from
one an operator set, so generated configs now record the chosen port
on a "# beads-chosen-listener-port: N" line after the managed marker.
The repicker moves the port only when the file is Beads-generated,
carries that record, and its listener.port is still the recorded port.
Otherwise the port is treated as pinned and Start fails with
ErrPortInUse. That includes configs generated before this change. It
rewrites only listener.port and the record, through a yaml.Node so the
rest of the file is kept, and writes the file atomically.
db-proxy-child installs it for the local backend.

The proxy's waitForServerReady also re-checks Running after its dial.
Start has already proved ownership, and a running dolt holds its
listener, so only a backend that exited between the two checks could
let a dial reach another process.

Tests:
- server: a held port is not accepted as ready (ErrPortInUse; this
  test fails on main), a repicker brings the server up on a new port
  that the pid record and DSN both use, and a declining repicker ends
  Start with ErrPortInUse.
- cmd/bd: the generated config records its port, a Beads-chosen port
  moves while hand edits survive, and a hand-set port, a config
  without the record, an operator config, and a stale in-use port are
  all refused with the file left untouched.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(dbproxy): move a taken managed port via a runtime config, never config.yaml

This reworks cd00c5acb after review. That commit recovered from a taken
Beads-chosen port by rewriting the managed config.yaml. That broke the
file's own contract ("Never rewritten afterward; hand edits are
preserved", #4986), and #5024 had deferred that contract change to an
RFC.

dolt sql-server has no command-line way around the file: with --config,
-P/--port is silently ignored (checked against dolt 2.1.8 and 2.2.0, in
both argument orders). So on ErrPortInUse the proxy child now writes
proxy-child.runtime-config.yaml (server.RuntimeConfigFileName) in the
server root. That file is the operator config with only listener.port
moved to a free port. The child relaunches dolt from it and records the
effective port where runtime readers already look: the backend pid
record and the DoltServer's dial/DSN config. The runtime config is
removed when the server stops, when Start fails, and by the next Start.
config.yaml is never written.

- server.PortRepicker becomes server.PortConflictPolicy. It only decides
  whether the port may move; the server does the move.
- bd's policy (managedPortConflictPolicy) allows a move when the file
  carries the managed marker and either:
  - has the port record and listener.port still equals it, or
  - is byte-identical to the config bd generated before the record
    existed, so existing unedited workspaces recover too.
- Everything else is pinned: operator configs, hand-set ports,
  hand-edited legacy files, and configs with ${...} placeholders (a
  runtime copy would put the expanded values on disk).
- The record line now says plainly that Beads runs on a free port
  without editing the file, and that deleting the line or changing
  listener.port pins the port. The record parser now requires the
  digits to end at a space or line end and to be in 1..65535.
- ErrPortInUse messages say what to do: free port P, set listener.port
  in <path> to a free port, or (for a generated file) delete it so
  Beads regenerates it. The give-up message names the last port tried.
- A dolt that never logs the ready line is still not accepted. A
  grace-period fallback would let a foreign listener through while dolt
  is still starting. The timeout error now names the missing line, says
  whether anything answered, and points at the escape hatch: at
  log_level warning, readiness is dial-only.
- Port-conflict detection matches go-mysql-server's "Port host:port
  already in use." and the Windows bind error, and requires the SQL port
  in the kernel's bind error, so a metrics or MCP listener failure is
  not taken for the SQL port.
- Spawn error paths reap with cmd.Wait(). cmd.WaitDelay is set, and a
  comment notes that the backend's output is now a pipe into the proxy
  child.

Tests:
- Output-watcher table tests: split, one-byte and CRLF writes, output
  past the 4 KiB tail, the MCP ready line, port boundaries, the
  go-mysql-server and Windows forms, another listener's bind error, the
  unix-socket warning, and nil log.
- A real dolt at log_level warning starts through dial-only readiness.
- With a stand-in dolt (the test binary in fake mode, wired in
  TestMain): Start gives up after maxStartPortAttempts, a missing ready
  line is diagnosed, plus a positive control.
- With real dolt: a move keeps config.yaml byte-identical, runs from the
  runtime config, and the runtime config is removed on Stop. A declining
  policy and the no-policy remedy are covered.
- The bd policy's allow and pin cases.
- The managed-local lifecycle test's config/pid port check accepts the
  runtime config.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(dbproxy): ask the port policy once, about the operator's port; copy raw config text

Re-review of the runtime-config rework found a regression. After the
first move, Start asked the PortConflictPolicy about the runtime port.
bd's policy re-reads config.yaml, whose listener.port is still the
operator's port, so it refused with "listener.port is A, not the in-use
port B". The "up to 5 ports" retry therefore never ran in production;
the fake-dolt test missed it because its policy always allowed.

Start now asks the policy once per Start, on the first conflict, about
the operator config's port. Ports Start picked itself are its own to move
again. Start also re-reads the operator config up front, so every Start
begins from that config's port.

The runtime config is now built from config.yaml's raw text
(servercfg.NewYamlConfig) instead of the env-interpolated
YamlConfigFromFile result. dolt interpolates the runtime file when it
reads it, so the old way expanded placeholders twice: "$$" escapes lost a
level and placeholder values landed on disk. The server reads the
runtime file back with interpolation for its own Dial/DSN view. Since
placeholders no longer expand on disk, bd's policy stops refusing
configs that contain them.

Tests:
- bd's real policy driving a real DoltServer with a stand-in dolt that
  reports every port taken: Start makes five launches on five distinct
  ports, starting with config.yaml's, then gives up. It is not refused
  on the second move, and config.yaml stays unchanged.
- A frozen byte-for-byte literal of the config bd v1.3.0/v1.3.1
  generates. The legacy render must equal it, and the policy must find
  it eligible.
- The runtime config keeps placeholders and "$$" verbatim and is mode
  0600, while the server dials the interpolated host.
- The give-up test asserts the policy is asked once, about the
  operator's port.
- The missing-ready-line test timeout is raised to 30s for the slow
  fake-dolt exec under race.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(dbproxy): classify a child that exits before its identity is captured

TestManagedPortConflictPolicy_ConsecutiveCollisions failed on the farm
with "capture child birth identity: procid: process is no longer
running", after 2 launches instead of 5. Its stand-in dolt reports
"Port N already in use." and exits immediately, and it exited before
Start captured its birth identity. Start treated that capture failure as
fatal, so an ErrPortInUse that Start could recover from became a hard
error. A real dolt that finds its port taken can exit just as fast, so
this race exists in the product, not only in the test.

Every spawn step before the child is handed to its supervising
goroutine (identity capture, root identity, pid record) now fails
through failSpawn. failSpawn kills and reaps the child; reaping also
drains its output into the watcher. The child's own exit then decides
the error:
- the child reported its port taken: ErrPortInUse, so the normal policy
  and retry path runs;
- the child exited by itself for another reason: "exited (status N)
  before startup completed";
- the child was alive and we killed it: the step's own error, as
  before.

On Windows, a killed child reports an ordinary exit code, so there an
exit cannot be told from a kill. Only the port-in-use classification
applies there.

procid.Capture is reached through a package var so tests can make the
capture lose the race deterministically.

Tests, using a shell-script stand-in dolt that starts in milliseconds:
- a fast port-in-use exit that beats the capture is ErrPortInUse, and
  with a policy it is retried up to the 5-port budget;
- a fast exit for another reason reports its status;
- a capture failure while the child is alive stays fatal and kills the
  child;
- ten immediate port-in-use exits with the real capture are all
  ErrPortInUse.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-04 04:24:32 -07:00

523 lines
18 KiB
Go

package main
import (
"bytes"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"github.com/dolthub/dolt/go/libraries/doltcore/servercfg"
"github.com/dolthub/dolt/go/libraries/utils/filesys"
"gopkg.in/yaml.v3"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/doltserver"
"github.com/steveyegge/beads/internal/storage/dbproxy/proxy"
)
const managedListenerHostRemediation = "set listener.host to 127.0.0.1 (or another 127.0.0.0/8 / ::1 " +
"loopback address); for non-local topology use " +
"--proxied-server-external-host with --proxied-server-external-port, " +
"--proxied-server-external-socket-path, or switch to non-proxied server mode"
const managedProxiedServerConfigMarker = "# Generated by Beads on first run - safe to delete (will be regenerated). " +
"Never rewritten afterward; hand edits are preserved. See gastownhall/beads#4986.\n"
func isManagedProxiedServerConfig(body []byte) bool {
return bytes.HasPrefix(body, []byte(managedProxiedServerConfigMarker))
}
const (
proxiedServerConfigName = "config.yaml"
proxiedServerLogName = "server.log"
)
func proxiedServerRoot(beadsDir string) string {
return doltserver.ResolveDoltDir(beadsDir)
}
func proxiedServerConfigPath(beadsDir string) string {
return filepath.Join(proxiedServerRoot(beadsDir), proxiedServerConfigName)
}
func proxiedServerLogPath(beadsDir string) string {
return filepath.Join(proxiedServerRoot(beadsDir), proxiedServerLogName)
}
func envOrAbsJoin(envName, beadsDir string) string {
p := os.Getenv(envName)
if p == "" {
return ""
}
if filepath.IsAbs(p) {
return p
}
return filepath.Join(beadsDir, p)
}
// resolveProxiedServerRootPath delegates to the exported implementation in
// internal/doltserver so the workspace-gate resolver and the proxy plumbing
// share one root derivation (env → client-info sidecar → default data dir)
// and cannot drift. Note the shared implementation resolves the default via
// the side-effect-free DoltDirPath — same path as proxiedServerRoot, but it
// never mkdirs the shared-server tree just to answer "where is the root".
func resolveProxiedServerRootPath(beadsDir string) (string, error) {
return doltserver.ResolveProxiedServerRootPath(beadsDir)
}
func resolveProxiedServerConfigPath(beadsDir string) (path string, isCustom bool, err error) {
if p := envOrAbsJoin("BEADS_PROXIED_SERVER_CONFIG", beadsDir); p != "" {
return p, true, nil
}
info, err := configfile.LoadProxiedServerClientInfo(beadsDir)
if err != nil {
return "", false, err
}
if p := info.ResolvedConfigPath(beadsDir); p != "" {
return p, true, nil
}
root, err := resolveProxiedServerRootPath(beadsDir)
if err != nil {
return "", false, err
}
return filepath.Join(root, proxiedServerConfigName), false, nil
}
func resolveProxiedServerLogPath(beadsDir string) (path string, isCustom bool, err error) {
if p := envOrAbsJoin("BEADS_PROXIED_SERVER_LOG", beadsDir); p != "" {
return p, true, nil
}
info, err := configfile.LoadProxiedServerClientInfo(beadsDir)
if err != nil {
return "", false, err
}
if p := info.ResolvedLogPath(beadsDir); p != "" {
return p, true, nil
}
root, err := resolveProxiedServerRootPath(beadsDir)
if err != nil {
return "", false, err
}
return filepath.Join(root, proxiedServerLogName), false, nil
}
func ensureProxiedServerConfig(beadsDir string) (string, error) {
path, err := resolveOrCreateProxiedServerConfig(beadsDir)
if err != nil {
return "", err
}
if err := validateProxiedServerConfig(path); err != nil {
return "", fmt.Errorf("ensureProxiedServerConfig: %w", err)
}
return path, nil
}
func resolveOrCreateProxiedServerConfig(beadsDir string) (string, error) {
path, isCustom, err := resolveProxiedServerConfigPath(beadsDir)
if err != nil {
return "", err
}
if isCustom {
info, err := os.Stat(path)
if err != nil {
return "", fmt.Errorf("ensureProxiedServerConfig: custom config %s: %w", path, err)
}
if !info.Mode().IsRegular() {
return "", fmt.Errorf("ensureProxiedServerConfig: custom config %s: not a regular file", path)
}
return path, nil
}
root := filepath.Dir(path)
if err := os.MkdirAll(root, config.BeadsDirPerm); err != nil {
return "", fmt.Errorf("ensureProxiedServerConfig: mkdir %s: %w", root, err)
}
switch _, err := os.Stat(path); {
case err == nil:
return path, nil
case !os.IsNotExist(err):
return "", fmt.Errorf("ensureProxiedServerConfig: stat %s: %w", path, err)
}
port, err := proxy.PickFreePort()
if err != nil {
return "", fmt.Errorf("ensureProxiedServerConfig: pick free port: %w", err)
}
body, err := renderProxiedServerConfig(port)
if err != nil {
return "", fmt.Errorf("ensureProxiedServerConfig: render YAML: %w", err)
}
if err := atomicWriteFile(resolveConfigWriteTarget(path), body); err != nil {
return "", fmt.Errorf("ensureProxiedServerConfig: write %s: %w", path, err)
}
return path, nil
}
// resolveConfigWriteTarget resolves path to its physical location before
// an atomic rewrite. os.Rename's destination argument does not follow
// symlinks — it unlinks and replaces whatever is AT that path, symlink or
// not — so writing straight to a symlinked config.yaml would silently
// replace the symlink itself with a regular file instead of updating the
// file it points at. Falls back to path unresolved when it does not exist
// yet (filepath.EvalSymlinks errors on a missing path), which covers both
// the ordinary "no config.yaml yet" case and a dangling symlink.
func resolveConfigWriteTarget(path string) string {
resolved, err := filepath.EvalSymlinks(path)
if err != nil {
return path
}
return resolved
}
// Validators below emit source-neutral errors. Callers wrap with whichever
// label is meaningful at their site: CLI callers prepend the flag name
// (e.g. "--proxied-server-config-path"); runtime callers (uow factory, etc.)
// prepend whatever label fits — the path may have come from env var or
// the proxied_server_client_info.json sidecar, not necessarily a flag.
func validateProxiedServerConfig(path string) error {
info, err := os.Stat(path)
if err != nil {
return fmt.Errorf("%s: %w", path, err)
}
if !info.Mode().IsRegular() {
return fmt.Errorf("%s: not a regular file", path)
}
cfg, err := servercfg.YamlConfigFromFile(filesys.LocalFS, path)
if err != nil {
return fmt.Errorf("%s: parse: %w", path, err)
}
if err := validateManagedServerConfigPolicy(cfg); err != nil {
return fmt.Errorf("%s: %w", path, err)
}
return nil
}
// validateManagedServerConfigPolicy enforces the trust boundary for the Dolt
// child that Beads launches with root and an empty password: every listener
// the config can open must stay loopback-only, so the whole config is in
// scope, not just listener.host. External proxied topology never calls this
// validator because it launches no managed child.
func validateManagedServerConfigPolicy(cfg servercfg.ServerConfig) error {
// listener.host policy: an explicit numeric loopback IP, nothing else.
// An omitted host is rejected rather than trusted: servercfg resolves it
// to DefaultHost ("localhost"), and CheckForUnixSocket treats a
// "localhost" host as license to also open the shared-namespace default
// unix socket — strictly worse than the explicit hostname it looks like.
if yc, ok := cfg.(*servercfg.YAMLConfig); ok && yc.ListenerConfig.HostStr == nil {
return fmt.Errorf(
"managed proxied-server listener.host is omitted (Dolt would default to %q, "+
"which can also open the default unix socket) and must be a numeric loopback IP literal: %s",
servercfg.DefaultHost, managedListenerHostRemediation,
)
}
host := cfg.Host()
ip := net.ParseIP(host)
if ip == nil || !ip.IsLoopback() {
return fmt.Errorf(
"managed proxied-server listener.host %q must be a numeric loopback IP literal: %s",
host, managedListenerHostRemediation,
)
}
// A unix socket bypasses the loopback TCP trust boundary entirely
// (shared filesystem namespace). Socket() maps an explicitly empty
// listener.socket to Dolt's default socket path, so it is rejected too.
if socket := cfg.Socket(); socket != "" {
return fmt.Errorf(
"managed proxied-server config sets listener.socket %q, which bypasses the loopback trust boundary: "+
"remove listener.socket; %s",
socket, managedListenerHostRemediation,
)
}
// remotesapi.port opens an HTTP+gRPC listener on all interfaces; there
// is no host knob for it, so its presence alone breaks the boundary.
if port := cfg.RemotesapiPort(); port != nil {
return fmt.Errorf(
"managed proxied-server config sets remotesapi.port %d, which listens on all interfaces: "+
"remove the remotesapi block; %s",
*port, managedListenerHostRemediation,
)
}
// cluster.remotesapi.port likewise listens on all interfaces.
if cfg.ClusterConfig() != nil {
return fmt.Errorf(
"managed proxied-server config sets a cluster block, whose remotesapi listens on all interfaces: "+
"remove the cluster block; %s",
managedListenerHostRemediation,
)
}
return nil
}
// validateManagedProxiedServerConfigAtInit validates the effective existing
// managed-local config before init performs filesystem mutations. A missing
// Beads-default path is valid because init/runtime will generate the
// loopback-only config. Missing custom paths remain hard errors.
//
// explicitRootPath is the --proxied-server-root-path flag value: at this
// point the sidecar is not persisted yet, so resolveProxiedServerConfigPath
// cannot see the flag and it must be applied here. An explicit
// --proxied-server-config-path needs no handling here — init.go already
// validated it at flag-parse time, and when no config env override is set it
// IS the effective config, so there is nothing further to check.
func validateManagedProxiedServerConfigAtInit(beadsDir, explicitPath, explicitRootPath string) error {
if explicitPath != "" && os.Getenv("BEADS_PROXIED_SERVER_CONFIG") == "" {
return nil
}
path, isCustom, err := resolveProxiedServerConfigPath(beadsDir)
if err != nil {
return err
}
if !isCustom && explicitRootPath != "" && os.Getenv("BEADS_PROXIED_SERVER_ROOT_PATH") == "" {
path = filepath.Join(explicitRootPath, proxiedServerConfigName)
}
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) && !isCustom {
return nil
}
return fmt.Errorf("%s: %w", path, err)
}
return validateProxiedServerConfig(path)
}
func validateProxiedServerRootPath(path string) error {
switch info, err := os.Stat(path); {
case err == nil:
if !info.IsDir() {
return fmt.Errorf("%s: not a directory", path)
}
case !os.IsNotExist(err):
return fmt.Errorf("%s: %w", path, err)
}
return nil
}
func validateProxiedServerLogPath(path string) error {
parent := filepath.Dir(path)
parentInfo, err := os.Stat(parent)
if err != nil {
return fmt.Errorf("%s: parent directory: %w", path, err)
}
if !parentInfo.IsDir() {
return fmt.Errorf("%s: parent %s is not a directory", path, parent)
}
switch info, err := os.Stat(path); {
case err == nil:
if !info.Mode().IsRegular() {
return fmt.Errorf("%s: not a regular file", path)
}
case !os.IsNotExist(err):
return fmt.Errorf("%s: %w", path, err)
}
return nil
}
func renderProxiedServerConfig(port int) ([]byte, error) {
host := proxiedServerListenerHost
logLevel := string(servercfg.LogLevel_Info)
yc := &servercfg.YAMLConfig{
LogLevelStr: &logLevel,
ListenerConfig: servercfg.ListenerYAMLConfig{
HostStr: &host,
PortNumber: &port,
},
}
archiveLevel := 0
yc.BehaviorConfig.AutoGCBehavior = &servercfg.AutoGCBehaviorYAMLConfig{
ArchiveLevel_: &archiveLevel,
}
body, err := yaml.Marshal(yc)
if err != nil {
return nil, err
}
out := []byte(managedProxiedServerConfigMarker + managedPortRecordLine(port))
return append(out, body...), nil
}
const proxiedServerListenerHost = "127.0.0.1"
// managedPortRecordPrefix starts the comment line, right after the managed
// marker, that records the listener port Beads chose. The dolt sql-server
// binds that port only after the proxy child starts it, so another process
// can take it first; the record lets the child tell a port Beads chose from
// one an operator set (see managedPortConflictPolicy). The file itself is
// still never rewritten: a moved port lives only in the proxy child's runtime
// config (server.RuntimeConfigFileName).
const managedPortRecordPrefix = "# beads-chosen-listener-port: "
func managedPortRecordLine(port int) string {
return fmt.Sprintf("%s%d (Beads chose this port. If another process holds it when the server starts, Beads runs the server on a free port for that run, without editing this file. To pin a port, set listener.port to another value or delete this line.)\n",
managedPortRecordPrefix, port)
}
// renderLegacyProxiedServerConfig is renderProxiedServerConfig as it was
// before the port record existed: the marker followed directly by the YAML.
func renderLegacyProxiedServerConfig(port int) ([]byte, error) {
body, err := renderProxiedServerConfig(port)
if err != nil {
return nil, err
}
return append([]byte(managedProxiedServerConfigMarker), body[len(managedProxiedServerConfigMarker)+len(managedPortRecordLine(port)):]...), nil
}
// managedPortConflictPolicy is the managed-local backend's
// server.PortConflictPolicy. It lets the proxy child run the dolt sql-server
// on a free port (through a runtime config; configPath is never modified)
// only when configPath's listener.port is a port Beads chose:
// - the file carries the managed marker and the port record, and
// listener.port still equals the recorded port; or
// - the file is byte-identical to a config Beads generated before the
// record existed (any hand edit makes the bytes differ).
//
// Anything else (an operator's own config, a hand-set port, a hand-edited
// legacy config) is pinned, and the error says what to do.
func managedPortConflictPolicy(configPath string, inUsePort int) error {
body, err := os.ReadFile(configPath) // #nosec G304 -- the proxy child's own --config path
if err != nil {
return fmt.Errorf("read %s: %w", configPath, err)
}
remedy := fmt.Sprintf("free port %d, or set listener.port in %s to a free port", inUsePort, configPath)
if !isManagedProxiedServerConfig(body) {
return fmt.Errorf("%s is not a Beads-generated config, so its port is pinned; %s", configPath, remedy)
}
remedy += ", or delete " + configPath + " so Beads regenerates it"
cfg, err := servercfg.NewYamlConfig(body)
if err != nil {
return fmt.Errorf("parse %s: %w", configPath, err)
}
current := cfg.Port()
if current != inUsePort {
return fmt.Errorf("%s: listener.port is %d, not the in-use port %d; %s", configPath, current, inUsePort, remedy)
}
if recorded, _, ok := cutManagedPortRecord(body[len(managedProxiedServerConfigMarker):]); ok {
if current != recorded {
return fmt.Errorf("%s: listener.port %d was set by hand (Beads chose %d), so it is pinned; %s", configPath, current, recorded, remedy)
}
return nil
}
legacy, err := renderLegacyProxiedServerConfig(current)
if err != nil {
return fmt.Errorf("render legacy config: %w", err)
}
if bytes.Equal(body, legacy) {
return nil
}
return fmt.Errorf("%s was edited by hand and has no %q record, so its listener.port is pinned; %s",
configPath, strings.TrimSpace(managedPortRecordPrefix), remedy)
}
// cutManagedPortRecord splits the port record line off the front of rest
// (the managed config after its marker) and returns the recorded port and
// the remaining YAML. The digits must end at a space or the line end and
// name a valid TCP port.
func cutManagedPortRecord(rest []byte) (port int, yamlBody []byte, ok bool) {
if !bytes.HasPrefix(rest, []byte(managedPortRecordPrefix)) {
return 0, nil, false
}
line, after, found := bytes.Cut(rest, []byte("\n"))
if !found {
return 0, nil, false
}
digits := line[len(managedPortRecordPrefix):]
end := 0
for end < len(digits) && digits[end] >= '0' && digits[end] <= '9' {
end++
}
if end == 0 || (end < len(digits) && digits[end] != ' ') {
return 0, nil, false
}
port, err := strconv.Atoi(string(digits[:end]))
if err != nil || port < 1 || port > 65535 {
return 0, nil, false
}
return port, after, true
}
// TODO: this needs to return a dolt server uow provider as the global
// uow provider used by all commands
// func newProxiedServerStore(ctx context.Context, cfg *dolt.Config) (storage.DoltStorage, error) {
// if cfg == nil {
// return nil, fmt.Errorf("newProxiedServerStore: cfg is nil")
// }
// if cfg.BeadsDir == "" {
// return nil, fmt.Errorf("newProxiedServerStore: cfg.BeadsDir must be set")
// }
// if cfg.Database == "" {
// return nil, fmt.Errorf("newProxiedServerStore: cfg.Database must be set")
// }
//
// doltBin, err := exec.LookPath("dolt")
// if err != nil {
// return nil, fmt.Errorf("newProxiedServerStore: dolt is not installed (not found in PATH); install from https://docs.dolthub.com/introduction/installation: %w", err)
// }
//
// persisted, _ := configfile.Load(cfg.BeadsDir)
//
// rootPath, isCustomRoot := resolveProxiedServerRootPath(cfg.BeadsDir, persisted)
// if isCustomRoot {
// if err := validateProxiedServerRootPath(rootPath); err != nil {
// return nil, err
// }
// }
//
// configPath, err := ensureProxiedServerConfig(cfg.BeadsDir, persisted)
// if err != nil {
// return nil, err
// }
//
// logPath, isCustomLog := resolveProxiedServerLogPath(cfg.BeadsDir, persisted)
// if isCustomLog {
// if err := validateProxiedServerLogPath(logPath); err != nil {
// return nil, err
// }
// }
//
// name, email := cfg.CommitterName, cfg.CommitterEmail
// if name == "" || email == "" {
// fallbackName, fallbackEmail := proxiedServerCommitter()
// if name == "" {
// name = fallbackName
// }
// if email == "" {
// email = fallbackEmail
// }
// }
//
// return doltserver.NewDoltServerStore(
// ctx,
// rootPath,
// cfg.BeadsDir,
// cfg.Database,
// name, email,
// logPath,
// configPath,
// proxy.BackendLocalServer,
// false, // autoSyncToOriginRemote — wired in a future iteration
// "root",
// "", // rootPassword: proxy is loopback-only, no auth
// doltBin,
// )
// }
func proxiedServerCommitter() (string, string) {
name, email := "beads", "beads@localhost"
if out, err := exec.Command("git", "config", "user.name").Output(); err == nil {
if v := strings.TrimSpace(string(out)); v != "" {
name = v
}
}
if out, err := exec.Command("git", "config", "user.email").Output(); err == nil {
if v := strings.TrimSpace(string(out)); v != "" {
email = v
}
}
return name, email
}