* fix(proxy): fail fast with a MySQL error when the external upstream is unreachable A proxied-server command against a stopped external Dolt upstream stalled ~20-30s before failing with a bare "invalid connection". The local db proxy stays up, so on a refused backend dial (or a front such as stunnel/socat that accepts and closes because its own upstream is gone) it simply closed the client connection. The MySQL driver reports that as invalid connection / unexpected EOF, which the uow bootstrap ping (#6003) classifies as a transient drop and retries with exponential backoff for its whole 30s budget. Retrying cannot help: the proxy already proved the upstream at its own startup, and the outage is the upstream's. The proxy now answers such a connection itself with a MySQL ERR packet (2003, HY000) in place of the server greeting, naming the upstream and the cause, exactly as a real server refuses a connection before the handshake. The driver surfaces it as a *mysql.MySQLError, which the bootstrap retry already treats as permanent, so the command fails in ~0.1s with an actionable message. Only shapes that prove the upstream is not serving qualify: ECONNREFUSED/ENOENT/EHOSTUNREACH/ENETUNREACH on dial, or a backend that reaches EOF having sent zero bytes (a MySQL server always speaks first). A dial timeout or a drop after the greeting keeps the plain close and the client's transient retry. External backends only: a managed (local sidecar) backend is owned by the proxy and its dial can be refused transiently while bd drives it (the full proxied lane caught TestProxiedServerInitExplicitBeadsDirIsAuthoritative hitting exactly that mid-init when this applied to every backend), so managed backends keep the bare close and the client's bootstrap retry. TestExternalProxyOutageAndRestoreReDialsTCPAndUnix asserted the old silent close during an outage; it now asserts the ERR packet. With the latency fixed, TestProxiedOutageReconnectAcceptanceMatrix is renamed into the proxied discovery pattern as TestProxiedServerOutageReconnectAcceptanceMatrix and placed in the Bazel 30-shard block by gen_proxied_shard_manifest.py's incremental --write (shard 8). The frozen legacy 15-shard block is untouched; the test hash-distributes there like every other test added since it was frozen. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(proxy,uow): retry the proxy's upstream-outage report for ~1s; hedge the zero-byte case Review follow-up to the fail-fast change. A zero-byte close from the upstream is not proof it is down: Dolt closes queued connections without a byte when max_connections/back_log are full, when a queued connection times out, and while it shuts down for a restart; an L4 front does the same while its target is replaced. Its report now says "closed the connection before the MySQL greeting (down, restarting, or at its connection limit)" instead of "unreachable", and the comment no longer claims proof. Refusals and endpoint churn also lost #6003's retry entirely, so an external Dolt restart or a Service with no ready endpoints failed a command at once. The client now retries the proxy's report (proxy.IsUpstreamOutageError: 2003 with the "beads db proxy: " prefix) for upstreamOutageRetryWindow (1s) from the first time it sees it, with the backoff clamped so the last attempt lands at the window's end; other transient errors keep the 30s budget. A real outage still fails in about a second, inside the acceptance test's 3s bound. Also: the dial report drops Go call-site wrapping ("dial tcp H:P: connection refused"), truncation keeps UTF-8 intact, the comment states how the packet differs from a real server's pre-handshake ERR (keeps the '#'+SQLSTATE marker for vitess; 2003 is a client code chosen on purpose), a Stats counter for reported outages, and the isTransientPingError paragraph is reflowed and corrected. Tests: pingWithRetry retries the report inside the window and gives up at its end without using the full budget; openDB against a front that plays the proxy (its real packet) and comes back 300ms after the first connection succeeds in one call, and fails in about the window when it never does; NewProxyServer enables the report for external backends only; the dial message carries no Go type names; rune-safe truncation. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * test(proxied): fail, not skip, socat-bridged subtests in the Bazel lane The external-unix front-door matrix subtest and both outage/reconnect matrix subtests bridge an external endpoint with socat and skipped when it was missing, so they could stop running without anyone noticing (the parent test still passes). requireSocat now fails them when BEADS_TEST_REQUIRE_SOCAT=1, which //cmd/bd:bd_proxied_test sets (its remote workers have socat; a recent main run's external-unix subtest passed there). The legacy GitHub 15-shard jobs have no socat and leave it unset, so the subtests keep skipping there. The check now runs before the upstream Dolt server is started, so a skip no longer pays for one. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * ci(proxied): measured weight for the outage matrix; pin it to legacy shard 1 Give TestProxiedServerOutageReconnectAcceptanceMatrix a duration entry (80s: local runs measured 55-79s alone, 60-70s in its shard, and review 68-109s under load) and re-place it with the generator's incremental --write: it moves from 30/8 to 30/11, one line, nothing else moved. The heaviest estimated shard is now 435s against a ~357s median; a repack would even that out but moves most assignments, so it is left to a separate CI-only change that refreshes all durations together. Legacy 15-shard block: the test would hash onto shard 14, already ~13.5 of the 15 min timeout on main. It is pinned to shard 1 (~6.5 min in recent main runs) under the block's reviewed-pin rule; it skips there today (no socat), and the pin keeps shard 14 safe if that changes. 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>
555 lines
16 KiB
Go
555 lines
16 KiB
Go
//go:build cgo
|
|
|
|
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"syscall"
|
|
"testing"
|
|
"time"
|
|
|
|
_ "github.com/go-sql-driver/mysql"
|
|
|
|
"github.com/steveyegge/beads/internal/storage/dbproxy/pidfile"
|
|
"github.com/steveyegge/beads/internal/storage/dbproxy/proxy"
|
|
"github.com/steveyegge/beads/internal/testutil"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
)
|
|
|
|
func requireProxiedServerEnv(t *testing.T) {
|
|
t.Helper()
|
|
if os.Getenv("BEADS_TEST_PROXIED_SERVER") != "1" {
|
|
t.Skip("set BEADS_TEST_PROXIED_SERVER=1 to run proxied-server integration tests")
|
|
}
|
|
testutil.RequireDoltBinary(t)
|
|
}
|
|
|
|
// requireSocat skips a test that needs socat as an external-endpoint bridge
|
|
// when it is not installed, or fails it when BEADS_TEST_REQUIRE_SOCAT=1. The
|
|
// Bazel proxied lane sets that (its workers have socat), so these subtests
|
|
// cannot silently stop running there; the legacy GitHub 15-shard lane has no
|
|
// socat and leaves it unset, so they skip there.
|
|
func requireSocat(t *testing.T) {
|
|
t.Helper()
|
|
if _, err := exec.LookPath("socat"); err != nil {
|
|
if os.Getenv("BEADS_TEST_REQUIRE_SOCAT") == "1" {
|
|
t.Fatalf("socat is required (BEADS_TEST_REQUIRE_SOCAT=1): %v", err)
|
|
}
|
|
t.Skipf("socat is required: %v", err)
|
|
}
|
|
}
|
|
|
|
func bdProxiedEnv(dir string) []string {
|
|
var env []string
|
|
for _, e := range os.Environ() {
|
|
if strings.HasPrefix(e, "BEADS_") {
|
|
continue
|
|
}
|
|
env = append(env, e)
|
|
}
|
|
return append(env,
|
|
"HOME="+dir,
|
|
"BEADS_DOLT_PROXIED_SERVER=1",
|
|
"BEADS_NO_DAEMON=1",
|
|
"BD_DISABLE_METRICS=1",
|
|
"BD_DISABLE_EVENT_FLUSH=1",
|
|
)
|
|
}
|
|
|
|
func bdProxiedRun(t *testing.T, bd, dir string, args ...string) ([]byte, error) {
|
|
t.Helper()
|
|
cmd := exec.Command(bd, args...)
|
|
cmd.Dir = dir
|
|
cmd.Env = bdProxiedEnv(dir)
|
|
stdout, stderr, err := runCommandBuffers(t, cmd)
|
|
if err != nil {
|
|
return append(stdout.Bytes(), stderr.Bytes()...), err
|
|
}
|
|
return stdout.Bytes(), nil
|
|
}
|
|
|
|
func bdProxiedCreate(t *testing.T, bd, dir string, args ...string) *types.Issue {
|
|
t.Helper()
|
|
fullArgs := append([]string{"create", "--json"}, args...)
|
|
out, err := bdProxiedRun(t, bd, dir, fullArgs...)
|
|
if err != nil {
|
|
t.Fatalf("bd create %s failed: %v\n%s", strings.Join(args, " "), err, out)
|
|
}
|
|
return parseIssueJSON(t, out)
|
|
}
|
|
|
|
func bdProxiedCreateSilent(t *testing.T, bd, dir string, args ...string) string {
|
|
t.Helper()
|
|
fullArgs := append([]string{"create", "--silent"}, args...)
|
|
out, err := bdProxiedRun(t, bd, dir, fullArgs...)
|
|
if err != nil {
|
|
t.Fatalf("bd create --silent %s failed: %v\n%s", strings.Join(args, " "), err, out)
|
|
}
|
|
return strings.TrimSpace(string(out))
|
|
}
|
|
|
|
func bdProxiedCreateFail(t *testing.T, bd, dir string, args ...string) string {
|
|
t.Helper()
|
|
fullArgs := append([]string{"create"}, args...)
|
|
out, err := bdProxiedRun(t, bd, dir, fullArgs...)
|
|
if err == nil {
|
|
t.Fatalf("bd create %s should have failed; got:\n%s", strings.Join(args, " "), out)
|
|
}
|
|
return string(out)
|
|
}
|
|
|
|
func bdProxiedList(t *testing.T, bd string, p proxiedProject, args ...string) string {
|
|
t.Helper()
|
|
stdout, _ := bdProxiedListCapture(t, bd, p, args...)
|
|
return stdout
|
|
}
|
|
|
|
func bdProxiedListJSON(t *testing.T, bd string, p proxiedProject, args ...string) []*types.IssueWithCounts {
|
|
t.Helper()
|
|
fullArgs := append([]string{"list", "--json"}, args...)
|
|
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, fullArgs...)
|
|
if err != nil {
|
|
t.Fatalf("bd list --json %s failed: %v\nstdout:\n%s\nstderr:\n%s",
|
|
strings.Join(args, " "), err, stdout, stderr)
|
|
}
|
|
start := strings.Index(stdout, "[")
|
|
if start < 0 {
|
|
if strings.Contains(stdout, "null") || strings.TrimSpace(stdout) == "" {
|
|
return nil
|
|
}
|
|
t.Fatalf("no JSON array found in output:\n%s", stdout)
|
|
}
|
|
var issues []*types.IssueWithCounts
|
|
if err := json.Unmarshal([]byte(stdout[start:]), &issues); err != nil {
|
|
t.Fatalf("failed to parse JSON list output: %v\nraw: %s", err, stdout[start:])
|
|
}
|
|
return issues
|
|
}
|
|
|
|
func bdProxiedListCapture(t *testing.T, bd string, p proxiedProject, args ...string) (string, string) {
|
|
t.Helper()
|
|
fullArgs := append([]string{"list"}, args...)
|
|
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, fullArgs...)
|
|
if err != nil {
|
|
t.Fatalf("bd list %s failed: %v\nstdout:\n%s\nstderr:\n%s",
|
|
strings.Join(args, " "), err, stdout, stderr)
|
|
}
|
|
return stdout, stderr
|
|
}
|
|
|
|
func bdProxiedListFail(t *testing.T, bd string, p proxiedProject, args ...string) string {
|
|
t.Helper()
|
|
fullArgs := append([]string{"list"}, args...)
|
|
stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, fullArgs...)
|
|
if err == nil {
|
|
t.Fatalf("expected bd list %s to fail, but it succeeded:\nstdout:\n%s\nstderr:\n%s",
|
|
strings.Join(args, " "), stdout, stderr)
|
|
}
|
|
return stdout + stderr
|
|
}
|
|
|
|
func bdProxiedRunBuffers(t *testing.T, bd, dir string, args ...string) (string, string, error) {
|
|
t.Helper()
|
|
return bdProxiedRunBuffersWithEnv(t, bd, dir, nil, args...)
|
|
}
|
|
|
|
// bdProxiedRunBuffersWithEnv is bdProxiedRunBuffers with extra environment
|
|
// variables appended after the standard proxied env (so they can override
|
|
// it, e.g. BEADS_MAX_ROWS for the proxied-server MaxRows-rejection tests).
|
|
func bdProxiedRunBuffersWithEnv(t *testing.T, bd, dir string, envExtras []string, args ...string) (string, string, error) {
|
|
t.Helper()
|
|
cmd := exec.Command(bd, args...)
|
|
cmd.Dir = dir
|
|
cmd.Env = append(bdProxiedEnv(dir), envExtras...)
|
|
var stdout, stderr bytes.Buffer
|
|
cmd.Stdout = &stdout
|
|
cmd.Stderr = &stderr
|
|
err := cmd.Run()
|
|
return stdout.String(), stderr.String(), err
|
|
}
|
|
|
|
// bdProxiedRunDeadline is bdProxiedRunBuffers for a command that may never exit
|
|
// on its own — `bd list --watch` polls until it is interrupted. It reports
|
|
// whether the deadline was what stopped it, so a case can tell "kept running"
|
|
// from "exited" instead of hanging the suite to find out.
|
|
func bdProxiedRunDeadline(t *testing.T, bd, dir string, timeout time.Duration, args ...string) (stdout, stderr string, err error, timedOut bool) {
|
|
t.Helper()
|
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
|
defer cancel()
|
|
cmd := exec.CommandContext(ctx, bd, args...)
|
|
cmd.Dir = dir
|
|
cmd.Env = bdProxiedEnv(dir)
|
|
var out, errOut bytes.Buffer
|
|
cmd.Stdout = &out
|
|
cmd.Stderr = &errOut
|
|
err = cmd.Run()
|
|
return out.String(), errOut.String(), err, ctx.Err() != nil
|
|
}
|
|
|
|
// bdProxiedRunUntilStderr starts a bd command that is NOT expected to exit and
|
|
// stops it the moment marker appears on stderr. reached is false when the
|
|
// command exited, or the timeout elapsed, before it got there.
|
|
//
|
|
// The alternative is to run such a command under a fixed deadline and wait the
|
|
// whole thing out, which costs the deadline on every green run and fails on a
|
|
// machine slow enough to render late. This waits for the state instead, so the
|
|
// timeout is only a bound on a hang.
|
|
func bdProxiedRunUntilStderr(t *testing.T, bd, dir, marker string, timeout time.Duration, args ...string) (stdout, stderr string, reached bool) {
|
|
t.Helper()
|
|
w := &markerWriter{marker: marker, seen: make(chan struct{})}
|
|
var out bytes.Buffer
|
|
cmd := exec.Command(bd, args...)
|
|
cmd.Dir = dir
|
|
cmd.Env = bdProxiedEnv(dir)
|
|
cmd.Stdout = &out
|
|
cmd.Stderr = w
|
|
if err := cmd.Start(); err != nil {
|
|
t.Fatalf("start bd %s: %v", strings.Join(args, " "), err)
|
|
}
|
|
exited := make(chan struct{})
|
|
go func() {
|
|
_ = cmd.Wait()
|
|
close(exited)
|
|
}()
|
|
select {
|
|
case <-w.seen:
|
|
reached = true
|
|
case <-exited:
|
|
case <-time.After(timeout):
|
|
}
|
|
_ = cmd.Process.Kill()
|
|
<-exited
|
|
return out.String(), w.String(), reached
|
|
}
|
|
|
|
// markerWriter buffers everything written to it and closes seen the first time
|
|
// marker shows up.
|
|
type markerWriter struct {
|
|
marker string
|
|
seen chan struct{}
|
|
|
|
mu sync.Mutex
|
|
buf bytes.Buffer
|
|
once sync.Once
|
|
}
|
|
|
|
func (w *markerWriter) Write(p []byte) (int, error) {
|
|
w.mu.Lock()
|
|
defer w.mu.Unlock()
|
|
n, err := w.buf.Write(p)
|
|
if strings.Contains(w.buf.String(), w.marker) {
|
|
w.once.Do(func() { close(w.seen) })
|
|
}
|
|
return n, err
|
|
}
|
|
|
|
func (w *markerWriter) String() string {
|
|
w.mu.Lock()
|
|
defer w.mu.Unlock()
|
|
return w.buf.String()
|
|
}
|
|
|
|
func bdProxiedUpdate(t *testing.T, bd, dir string, args ...string) []*types.Issue {
|
|
t.Helper()
|
|
fullArgs := append([]string{"update", "--json"}, args...)
|
|
out, err := bdProxiedRun(t, bd, dir, fullArgs...)
|
|
if err != nil {
|
|
t.Fatalf("bd update %s failed: %v\n%s", strings.Join(args, " "), err, out)
|
|
}
|
|
s := string(out)
|
|
start := strings.Index(s, "[")
|
|
if start < 0 {
|
|
t.Fatalf("no JSON array found in update output:\n%s", s)
|
|
}
|
|
var issues []*types.Issue
|
|
if err := json.Unmarshal([]byte(s[start:]), &issues); err != nil {
|
|
t.Fatalf("failed to parse update JSON: %v\nraw: %s", err, s[start:])
|
|
}
|
|
if len(issues) == 0 {
|
|
t.Fatalf("update returned empty JSON array:\n%s", s)
|
|
}
|
|
return issues
|
|
}
|
|
|
|
func bdProxiedUpdateOne(t *testing.T, bd, dir string, args ...string) *types.Issue {
|
|
t.Helper()
|
|
issues := bdProxiedUpdate(t, bd, dir, args...)
|
|
if len(issues) != 1 {
|
|
t.Fatalf("expected 1 issue in update output, got %d", len(issues))
|
|
}
|
|
return issues[0]
|
|
}
|
|
|
|
func bdProxiedUpdateRaw(t *testing.T, bd, dir string, args ...string) (string, string, error) {
|
|
t.Helper()
|
|
fullArgs := append([]string{"update"}, args...)
|
|
return bdProxiedRunBuffers(t, bd, dir, fullArgs...)
|
|
}
|
|
|
|
func bdProxiedUpdateFail(t *testing.T, bd, dir string, args ...string) string {
|
|
t.Helper()
|
|
stdout, stderr, err := bdProxiedUpdateRaw(t, bd, dir, args...)
|
|
if err == nil {
|
|
t.Fatalf("bd update %s should have failed; got:\nstdout:\n%s\nstderr:\n%s",
|
|
strings.Join(args, " "), stdout, stderr)
|
|
}
|
|
return stdout + stderr
|
|
}
|
|
|
|
func bdProxiedShow(t *testing.T, bd, dir, id string) *types.Issue {
|
|
t.Helper()
|
|
out, err := bdProxiedRun(t, bd, dir, "show", id, "--json")
|
|
if err != nil {
|
|
t.Fatalf("bd show %s --json failed: %v\n%s", id, err, out)
|
|
}
|
|
return parseIssueJSON(t, out)
|
|
}
|
|
|
|
func bdProxiedShowRaw(t *testing.T, bd, dir string, args ...string) string {
|
|
t.Helper()
|
|
fullArgs := append([]string{"show"}, args...)
|
|
out, err := bdProxiedRun(t, bd, dir, fullArgs...)
|
|
if err != nil {
|
|
t.Fatalf("bd show %s failed: %v\n%s", strings.Join(args, " "), err, out)
|
|
}
|
|
return string(out)
|
|
}
|
|
|
|
func bdProxiedShowFail(t *testing.T, bd, dir string, args ...string) (string, string) {
|
|
t.Helper()
|
|
fullArgs := append([]string{"show"}, args...)
|
|
stdout, stderr, err := bdProxiedRunBuffers(t, bd, dir, fullArgs...)
|
|
if err == nil {
|
|
t.Fatalf("bd show %s should have failed; got stdout:\n%s\nstderr:\n%s",
|
|
strings.Join(args, " "), stdout, stderr)
|
|
}
|
|
return stdout, stderr
|
|
}
|
|
|
|
func bdProxiedShowDetailsAll(t *testing.T, bd, dir string, args ...string) []map[string]interface{} {
|
|
t.Helper()
|
|
fullArgs := append([]string{"show", "--json"}, args...)
|
|
out, err := bdProxiedRun(t, bd, dir, fullArgs...)
|
|
if err != nil {
|
|
t.Fatalf("bd show --json %s failed: %v\n%s", strings.Join(args, " "), err, out)
|
|
}
|
|
s := strings.TrimSpace(string(out))
|
|
start := strings.IndexAny(s, "[{")
|
|
if start < 0 {
|
|
t.Fatalf("no JSON in show output: %s", s)
|
|
}
|
|
s = s[start:]
|
|
if strings.HasPrefix(s, "[") {
|
|
var arr []map[string]interface{}
|
|
if err := json.Unmarshal([]byte(s), &arr); err != nil {
|
|
t.Fatalf("parse show JSON array: %v\n%s", err, s)
|
|
}
|
|
return arr
|
|
}
|
|
var m map[string]interface{}
|
|
if err := json.Unmarshal([]byte(s), &m); err != nil {
|
|
t.Fatalf("parse show JSON: %v\n%s", err, s)
|
|
}
|
|
return []map[string]interface{}{m}
|
|
}
|
|
|
|
func bdProxiedShowDetailsFirst(t *testing.T, bd, dir string, args ...string) map[string]interface{} {
|
|
t.Helper()
|
|
arr := bdProxiedShowDetailsAll(t, bd, dir, args...)
|
|
if len(arr) == 0 {
|
|
t.Fatalf("bd show --json %s returned empty array", strings.Join(args, " "))
|
|
}
|
|
return arr[0]
|
|
}
|
|
|
|
type proxiedProject struct {
|
|
dir string
|
|
beadsDir string
|
|
proxyRoot string
|
|
database string
|
|
prefix string
|
|
}
|
|
|
|
func bdProxiedInitWithHooks(t *testing.T, bd, prefix string, hooks map[string]string, extraInitArgs ...string) proxiedProject {
|
|
t.Helper()
|
|
p := bdProxiedInitInternal(t, bd, prefix, false, extraInitArgs...)
|
|
hooksDir := filepath.Join(p.beadsDir, "hooks")
|
|
if err := os.MkdirAll(hooksDir, 0o755); err != nil {
|
|
t.Fatalf("mkdir hooks dir: %v", err)
|
|
}
|
|
for name, body := range hooks {
|
|
hookPath := filepath.Join(hooksDir, name)
|
|
if err := os.WriteFile(hookPath, []byte(body), 0o755); err != nil {
|
|
t.Fatalf("write hook %s: %v", name, err)
|
|
}
|
|
}
|
|
return p
|
|
}
|
|
|
|
func bdProxiedInit(t *testing.T, bd, prefix string, extraInitArgs ...string) proxiedProject {
|
|
t.Helper()
|
|
return bdProxiedInitInternal(t, bd, prefix, true, extraInitArgs...)
|
|
}
|
|
|
|
func bdProxiedInitInternal(t *testing.T, bd, prefix string, skipHooks bool, extraInitArgs ...string) proxiedProject {
|
|
t.Helper()
|
|
|
|
dir := t.TempDir()
|
|
initGitRepoAt(t, dir)
|
|
beadsDir := filepath.Join(dir, ".beads")
|
|
proxyRoot := filepath.Join(beadsDir, "dolt")
|
|
t.Cleanup(func() {
|
|
if err := proxy.Shutdown(proxyRoot); err != nil {
|
|
t.Logf("proxy.Shutdown(%s): %v", proxyRoot, err)
|
|
}
|
|
})
|
|
shutdownProxyOnInterrupt(t, proxyRoot)
|
|
|
|
baseArgs := []string{
|
|
"init",
|
|
"--proxied-server",
|
|
"--quiet",
|
|
"--prefix", prefix,
|
|
"--non-interactive",
|
|
"--skip-agents",
|
|
}
|
|
if skipHooks {
|
|
baseArgs = append(baseArgs, "--skip-hooks")
|
|
}
|
|
args := append(baseArgs, extraInitArgs...)
|
|
|
|
cmd := exec.Command(bd, args...)
|
|
cmd.Dir = dir
|
|
cmd.Env = bdProxiedEnv(dir)
|
|
stdout, stderr, err := runCommandBuffers(t, cmd)
|
|
if err != nil {
|
|
t.Fatalf("bd init --proxied-server failed: %v\nstdout:\n%s\nstderr:\n%s",
|
|
err, stdout.String(), stderr.String())
|
|
}
|
|
|
|
database := sanitizePrefixForDB(prefix)
|
|
|
|
return proxiedProject{
|
|
dir: dir,
|
|
beadsDir: beadsDir,
|
|
proxyRoot: proxyRoot,
|
|
database: database,
|
|
prefix: prefix,
|
|
}
|
|
}
|
|
|
|
func sanitizePrefixForDB(p string) string {
|
|
p = strings.TrimLeft(p, ".")
|
|
p = strings.TrimRight(p, "-")
|
|
p = strings.ReplaceAll(p, ".", "_")
|
|
if len(p) == 0 {
|
|
return "bd"
|
|
}
|
|
c := p[0]
|
|
if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_') {
|
|
p = "bd_" + p
|
|
}
|
|
return p
|
|
}
|
|
|
|
func shutdownProxyOnInterrupt(t *testing.T, proxyRoot string) {
|
|
t.Helper()
|
|
ch := make(chan os.Signal, 1)
|
|
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
|
|
done := make(chan struct{})
|
|
go func() {
|
|
select {
|
|
case <-ch:
|
|
_ = proxy.Shutdown(proxyRoot)
|
|
os.Exit(1)
|
|
case <-done:
|
|
}
|
|
}()
|
|
t.Cleanup(func() {
|
|
signal.Stop(ch)
|
|
close(done)
|
|
})
|
|
}
|
|
|
|
func openProxiedDB(t *testing.T, p proxiedProject) *sql.DB {
|
|
t.Helper()
|
|
pf, err := pidfile.Read(p.proxyRoot, proxy.PIDFileName)
|
|
if err != nil || pf == nil {
|
|
t.Fatalf("read proxy pidfile %s: %v (pf=%v)", p.proxyRoot, err, pf)
|
|
}
|
|
|
|
dsn := fmt.Sprintf("root:@tcp(127.0.0.1:%d)/%s?multiStatements=true&parseTime=true",
|
|
pf.Port, p.database)
|
|
db, err := sql.Open("mysql", dsn)
|
|
if err != nil {
|
|
t.Fatalf("sql.Open mysql %s: %v", dsn, err)
|
|
}
|
|
t.Cleanup(func() { _ = db.Close() })
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
if err := db.PingContext(ctx); err != nil {
|
|
t.Fatalf("ping proxied db: %v", err)
|
|
}
|
|
return db
|
|
}
|
|
|
|
func assertProxiedDepExists(t *testing.T, db *sql.DB, issueID, dependsOnID string) {
|
|
t.Helper()
|
|
var count int
|
|
err := db.QueryRowContext(context.Background(),
|
|
"SELECT COUNT(*) FROM dependencies WHERE issue_id = ? AND COALESCE(depends_on_issue_id, depends_on_wisp_id, depends_on_external) = ?",
|
|
issueID, dependsOnID).Scan(&count)
|
|
if err != nil {
|
|
t.Fatalf("query dep %s -> %s: %v", issueID, dependsOnID, err)
|
|
}
|
|
if count != 1 {
|
|
t.Fatalf("expected one dep row %s -> %s, got %d", issueID, dependsOnID, count)
|
|
}
|
|
}
|
|
|
|
func assertProxiedDepExistsWithType(t *testing.T, db *sql.DB, issueID, dependsOnID, depType string) {
|
|
t.Helper()
|
|
var count int
|
|
err := db.QueryRowContext(context.Background(),
|
|
"SELECT COUNT(*) FROM dependencies WHERE issue_id = ? AND COALESCE(depends_on_issue_id, depends_on_wisp_id, depends_on_external) = ? AND type = ?",
|
|
issueID, dependsOnID, depType).Scan(&count)
|
|
if err != nil {
|
|
t.Fatalf("query dep %s -> %s (%s): %v", issueID, dependsOnID, depType, err)
|
|
}
|
|
if count != 1 {
|
|
t.Fatalf("expected one dep row %s -> %s of type %s, got %d", issueID, dependsOnID, depType, count)
|
|
}
|
|
}
|
|
|
|
func getProxiedLabels(t *testing.T, db *sql.DB, issueID string) []string {
|
|
t.Helper()
|
|
rows, err := db.QueryContext(context.Background(),
|
|
"SELECT label FROM labels WHERE issue_id = ?", issueID)
|
|
if err != nil {
|
|
t.Fatalf("query labels for %s: %v", issueID, err)
|
|
}
|
|
defer rows.Close()
|
|
var out []string
|
|
for rows.Next() {
|
|
var l string
|
|
if err := rows.Scan(&l); err != nil {
|
|
t.Fatalf("scan label: %v", err)
|
|
}
|
|
out = append(out, l)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
t.Fatalf("label rows iter: %v", err)
|
|
}
|
|
return out
|
|
}
|