Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

FIX (mariadb\mysql): Add compression fallback from zstd to zlib and decompression

Rostislav Dugin3ae173a516f2
diff --git a/backend/internal/features/backups/backups/usecases/logical/mariadb/compression_probe.go b/backend/internal/features/backups/backups/usecases/logical/mariadb/compression_probe.go
new file mode 100644
index 00000000..d7c57320
--- /dev/null
+++ b/backend/internal/features/backups/backups/usecases/logical/mariadb/compression_probe.go
@@ -0,0 +1,122 @@
+package usecases_logical_mariadb
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+const (
+ compressionProbeTimeout = 15 * time.Second
+ compressionProbeTable = "__databasus_compression_probe__"
+)
+
+// networkCompressionCandidates has only the two entries MariaDB's protocol offers - zlib and
+// nothing. Managed providers that front the server with a proxy advertise compression the proxy
+// cannot actually negotiate, so the choice has to come from a handshake rather than be assumed.
+var networkCompressionCandidates = [][]string{
+ {"--compress"},
+ {},
+}
+
+// MyCnfFile holds the credentials and TLS mode, so the probe must not re-derive them; IsHttps only
+// adds the cert-verification opt-out that has no .my.cnf equivalent here.
+type CompressionProbeSpec struct {
+ MariadbDumpBin string
+ MyCnfFile string
+ DatabaseName string
+ DatabaseID uuid.UUID
+ IsHttps bool
+}
+
+func getNetworkCompressionLabel(candidate []string) string {
+ if len(candidate) == 0 {
+ return "uncompressed"
+ }
+
+ return strings.Join(candidate, " ")
+}
+
+// Error 2066 is CR_COMPRESSION_WRONGLY_CONFIGURED, raised client-side when the endpoint cannot
+// negotiate the requested algorithm.
+func isCompressionRejection(stderrStr string) bool {
+ return containsIgnoreCase(stderrStr, "compression algorithm") ||
+ containsIgnoreCase(stderrStr, "2066")
+}
+
+func (uc *CreateMariadbBackupUsecase) probeNetworkCompressionArgs(
+ ctx context.Context,
+ probe CompressionProbeSpec,
+) []string {
+ compressedCandidates := networkCompressionCandidates[:len(networkCompressionCandidates)-1]
+ chosenCompressionArgs := networkCompressionCandidates[len(networkCompressionCandidates)-1]
+
+ for _, candidate := range compressedCandidates {
+ if uc.isNetworkCompressionAccepted(ctx, probe, candidate) {
+ chosenCompressionArgs = candidate
+ break
+ }
+ }
+
+ uc.logger.Info(
+ fmt.Sprintf("negotiated MariaDB network compression: %s",
+ getNetworkCompressionLabel(chosenCompressionArgs)),
+ "database_id", probe.DatabaseID,
+ )
+
+ return chosenCompressionArgs
+}
+
+// isNetworkCompressionAccepted dials with mariadb-dump rather than the interactive client so the
+// probe cannot disagree with the dump about which binary loads. Naming a table that cannot exist
+// keeps the attempt O(1): the handshake — where compression is negotiated — happens first, then
+// mariadb-dump gives up. Only a compression complaint counts as a rejection; any other failure
+// (unreachable host, bad credentials) recurs identically for every candidate, so it is left for
+// the dump to report with a precise message.
+func (uc *CreateMariadbBackupUsecase) isNetworkCompressionAccepted(
+ ctx context.Context,
+ probe CompressionProbeSpec,
+ candidate []string,
+) bool {
+ probeCtx, cancel := context.WithTimeout(ctx, compressionProbeTimeout)
+ defer cancel()
+
+ args := append([]string{"--defaults-file=" + probe.MyCnfFile}, candidate...)
+
+ if probe.IsHttps {
+ args = append(args, "--skip-ssl-verify-server-cert")
+ }
+
+ args = append(args, "--no-data", probe.DatabaseName, compressionProbeTable)
+
+ var probeStderr bytes.Buffer
+
+ cmd := exec.CommandContext(probeCtx, probe.MariadbDumpBin, args...)
+ cmd.Stdout = io.Discard
+ cmd.Stderr = &probeStderr
+ cmd.Env = append(os.Environ(),
+ "MYSQL_PWD=",
+ "LC_ALL=C.UTF-8",
+ "LANG=C.UTF-8",
+ )
+
+ if err := cmd.Run(); err != nil && isCompressionRejection(probeStderr.String()) {
+ uc.logger.Debug(
+ fmt.Sprintf("MariaDB rejected network compression: %s",
+ getNetworkCompressionLabel(candidate)),
+ "database_id", probe.DatabaseID,
+ "stderr", probeStderr.String(),
+ )
+
+ return false
+ }
+
+ return true
+}
diff --git a/backend/internal/features/backups/backups/usecases/logical/mariadb/compression_probe_test.go b/backend/internal/features/backups/backups/usecases/logical/mariadb/compression_probe_test.go
new file mode 100644
index 00000000..df11c668
--- /dev/null
+++ b/backend/internal/features/backups/backups/usecases/logical/mariadb/compression_probe_test.go
@@ -0,0 +1,103 @@
+package usecases_logical_mariadb
+
+import (
+ "log/slog"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/google/uuid"
+
+ mariadbtypes "databasus-backend/internal/features/databases/databases/mariadb"
+ "databasus-backend/internal/util/testing/containers"
+ "databasus-backend/internal/util/tools"
+)
+
+func Test_BuildMariadbDumpArgs_WhenCalled_OmitsCompressionFlags(t *testing.T) {
+ uc := &CreateMariadbBackupUsecase{}
+ database := &mariadbtypes.MariadbDatabase{Version: tools.MariadbVersion1011}
+
+ args := uc.buildMariadbDumpArgs(database)
+
+ for _, arg := range args {
+ if strings.Contains(arg, "compress") {
+ t.Fatalf("compression is negotiated by the probe, not the arg builder, got %q", arg)
+ }
+ }
+}
+
+func Test_NetworkCompressionCandidates_WhenRead_TryCompressThenUncompressed(t *testing.T) {
+ if len(networkCompressionCandidates) != 2 {
+ t.Fatalf("expected 2 candidates, got %v", networkCompressionCandidates)
+ }
+
+ if !slices.Equal(networkCompressionCandidates[0], []string{"--compress"}) {
+ t.Fatalf("expected --compress first, got %v", networkCompressionCandidates[0])
+ }
+
+ if len(networkCompressionCandidates[1]) != 0 {
+ t.Fatalf("expected uncompressed last, got %v", networkCompressionCandidates[1])
+ }
+}
+
+func Test_GetNetworkCompressionLabel_WhenCandidateIsEmpty_ReadsUncompressed(t *testing.T) {
+ if label := getNetworkCompressionLabel(nil); label != "uncompressed" {
+ t.Fatalf("expected \"uncompressed\", got %q", label)
+ }
+}
+
+func Test_IsCompressionRejection_OnError2066_ReportsRejection(t *testing.T) {
+ rejectionStderr := "mariadb-dump: Got error: 2066: Connection failed due to wrongly " +
+ "configured compression algorithm when trying to connect"
+
+ if !isCompressionRejection(rejectionStderr) {
+ t.Fatalf("expected error 2066 to read as a compression rejection, got %q", rejectionStderr)
+ }
+}
+
+func Test_IsCompressionRejection_OnUnrelatedFailure_ReportsNoRejection(t *testing.T) {
+ for _, unrelatedStderr := range []string{
+ "mariadb-dump: Got error: 1045: Access denied for user 'app'@'%' when trying to connect",
+ "mariadb-dump: Couldn't find table: \"__databasus_compression_probe__\"",
+ } {
+ if isCompressionRejection(unrelatedStderr) {
+ t.Fatalf("expected no compression rejection for %q", unrelatedStderr)
+ }
+ }
+}
+
+func Test_ProbeNetworkCompressionArgs_AgainstStockMariadb_SelectsCompress(t *testing.T) {
+ endpoint := containers.StartMariadb(t, "mariadb:10.11")
+
+ databaseName := containers.MariadbDatabase
+ database := &mariadbtypes.MariadbDatabase{
+ Version: tools.MariadbVersion1011,
+ Host: endpoint.Host,
+ Port: endpoint.Port,
+ Username: containers.MariadbUsername,
+ Database: &databaseName,
+ }
+ uc := &CreateMariadbBackupUsecase{logger: slog.New(slog.NewTextHandler(os.Stdout, nil))}
+
+ myCnfFile, err := uc.createTempMyCnfFile(database, containers.MariadbPassword)
+ if err != nil {
+ t.Fatalf("failed to create .my.cnf: %v", err)
+ }
+
+ t.Cleanup(func() { _ = os.RemoveAll(filepath.Dir(myCnfFile)) })
+
+ compressionArgs := uc.probeNetworkCompressionArgs(t.Context(), CompressionProbeSpec{
+ MariadbDumpBin: tools.GetMariadbExecutable(
+ tools.MariadbVersion1011, tools.MariadbExecutableMariadbDump,
+ ),
+ MyCnfFile: myCnfFile,
+ DatabaseName: databaseName,
+ DatabaseID: uuid.New(),
+ })
+
+ if !slices.Contains(compressionArgs, "--compress") {
+ t.Fatalf("expected --compress against a stock MariaDB, got %v", compressionArgs)
+ }
+}
diff --git a/backend/internal/features/backups/backups/usecases/logical/mariadb/create_backup_uc.go b/backend/internal/features/backups/backups/usecases/logical/mariadb/create_backup_uc.go
index d2be4bf8..d4421450 100644
--- a/backend/internal/features/backups/backups/usecases/logical/mariadb/create_backup_uc.go
+++ b/backend/internal/features/backups/backups/usecases/logical/mariadb/create_backup_uc.go
@@ -143,8 +143,6 @@ func (uc *CreateMariadbBackupUsecase) buildMariadbDumpArgs(
}
}
- args = append(args, "--compress")
-
args = append(args, "--max-allowed-packet=1G")
if mdb.IsHttps {
@@ -183,7 +181,16 @@ func (uc *CreateMariadbBackupUsecase) streamToStorage(
}
defer func() { _ = os.RemoveAll(filepath.Dir(myCnfFile)) }()
- fullArgs := append([]string{"--defaults-file=" + myCnfFile}, args...)
+ compressionArgs := uc.probeNetworkCompressionArgs(ctx, CompressionProbeSpec{
+ MariadbDumpBin: mariadbBin,
+ MyCnfFile: myCnfFile,
+ DatabaseName: *mdbConfig.Database,
+ DatabaseID: backup.DatabaseID,
+ IsHttps: mdbConfig.IsHttps,
+ })
+
+ fullArgs := append([]string{"--defaults-file=" + myCnfFile}, compressionArgs...)
+ fullArgs = append(fullArgs, args...)
cmd := exec.CommandContext(ctx, mariadbBin, fullArgs...)
uc.logger.Info("Executing MariaDB backup command", "command", cmd.String())
@@ -622,6 +629,15 @@ func (uc *CreateMariadbBackupUsecase) handleConnectionErrors(stderrStr string) e
)
}
+ if isCompressionRejection(stderrStr) {
+ return fmt.Errorf(
+ "MariaDB rejected the network compression algorithm that had just passed the "+
+ "pre-flight handshake probe. Compression is re-probed on every run, so retry "+
+ "the backup. stderr: %s",
+ stderrStr,
+ )
+ }
+
if containsIgnoreCase(stderrStr, "unknown database") {
return fmt.Errorf(
"MariaDB database does not exist. stderr: %s",
diff --git a/backend/internal/features/backups/backups/usecases/logical/mysql/compression_probe.go b/backend/internal/features/backups/backups/usecases/logical/mysql/compression_probe.go
new file mode 100644
index 00000000..07f7bc07
--- /dev/null
+++ b/backend/internal/features/backups/backups/usecases/logical/mysql/compression_probe.go
@@ -0,0 +1,135 @@
+package usecases_logical_mysql
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+
+ "databasus-backend/internal/util/tools"
+)
+
+const (
+ networkZstdCompressionLevel = 5
+ compressionProbeTimeout = 15 * time.Second
+ compressionProbeTable = "__databasus_compression_probe__"
+)
+
+// MyCnfFile holds the credentials and TLS mode, so the probe must not re-derive them.
+type CompressionProbeSpec struct {
+ MysqldumpBin string
+ MyCnfFile string
+ DatabaseName string
+ DatabaseID uuid.UUID
+}
+
+// getNetworkCompressionCandidates is ordered best ratio first and ends with the uncompressed
+// fallback. Managed providers that front MySQL with a proxy (e.g. Aliyun RDS) advertise algorithms
+// the proxy cannot actually negotiate, so the choice has to come from a handshake rather than from
+// the protocol_compression_algorithms server variable.
+func getNetworkCompressionCandidates(version tools.MysqlVersion) [][]string {
+ switch version {
+ case tools.MysqlVersion80, tools.MysqlVersion84, tools.MysqlVersion9:
+ return [][]string{
+ {
+ "--compression-algorithms=zstd",
+ fmt.Sprintf("--zstd-compression-level=%d", networkZstdCompressionLevel),
+ },
+ {"--compression-algorithms=zlib"},
+ {},
+ }
+ default:
+ return [][]string{
+ {"--compress"},
+ {},
+ }
+ }
+}
+
+func getNetworkCompressionLabel(candidate []string) string {
+ if len(candidate) == 0 {
+ return "uncompressed"
+ }
+
+ return strings.Join(candidate, " ")
+}
+
+// Error 2066 is CR_COMPRESSION_WRONGLY_CONFIGURED, raised client-side when the endpoint cannot
+// negotiate the requested algorithm.
+func isCompressionRejection(stderrStr string) bool {
+ return containsIgnoreCase(stderrStr, "compression algorithm") ||
+ containsIgnoreCase(stderrStr, "2066")
+}
+
+func (uc *CreateMysqlBackupUsecase) probeNetworkCompressionArgs(
+ ctx context.Context,
+ probe CompressionProbeSpec,
+ version tools.MysqlVersion,
+) []string {
+ candidates := getNetworkCompressionCandidates(version)
+ compressedCandidates := candidates[:len(candidates)-1]
+ chosenCompressionArgs := candidates[len(candidates)-1]
+
+ for _, candidate := range compressedCandidates {
+ if uc.isNetworkCompressionAccepted(ctx, probe, candidate) {
+ chosenCompressionArgs = candidate
+ break
+ }
+ }
+
+ uc.logger.Info(
+ fmt.Sprintf("negotiated MySQL network compression: %s",
+ getNetworkCompressionLabel(chosenCompressionArgs)),
+ "database_id", probe.DatabaseID,
+ )
+
+ return chosenCompressionArgs
+}
+
+// isNetworkCompressionAccepted dials with mysqldump rather than the interactive client so the probe
+// cannot disagree with the dump about which binary loads. Naming a table that cannot exist keeps
+// the attempt O(1): the handshake — where compression is negotiated — happens first, then mysqldump
+// gives up. Only a compression complaint counts as a rejection; any other failure (unreachable
+// host, bad credentials) recurs identically for every candidate, so it is left for the dump to
+// report with a precise message.
+func (uc *CreateMysqlBackupUsecase) isNetworkCompressionAccepted(
+ ctx context.Context,
+ probe CompressionProbeSpec,
+ candidate []string,
+) bool {
+ probeCtx, cancel := context.WithTimeout(ctx, compressionProbeTimeout)
+ defer cancel()
+
+ args := append([]string{"--defaults-file=" + probe.MyCnfFile}, candidate...)
+ args = append(args, "--no-data", probe.DatabaseName, compressionProbeTable)
+
+ var probeStderr bytes.Buffer
+
+ cmd := exec.CommandContext(probeCtx, probe.MysqldumpBin, args...)
+ cmd.Stdout = io.Discard
+ cmd.Stderr = &probeStderr
+ cmd.Env = append(os.Environ(),
+ "MYSQL_PWD=",
+ "LC_ALL=C.UTF-8",
+ "LANG=C.UTF-8",
+ )
+
+ if err := cmd.Run(); err != nil && isCompressionRejection(probeStderr.String()) {
+ uc.logger.Debug(
+ fmt.Sprintf("MySQL rejected network compression: %s",
+ getNetworkCompressionLabel(candidate)),
+ "database_id", probe.DatabaseID,
+ "stderr", probeStderr.String(),
+ )
+
+ return false
+ }
+
+ return true
+}
diff --git a/backend/internal/features/backups/backups/usecases/logical/mysql/compression_probe_test.go b/backend/internal/features/backups/backups/usecases/logical/mysql/compression_probe_test.go
new file mode 100644
index 00000000..fbfdd307
--- /dev/null
+++ b/backend/internal/features/backups/backups/usecases/logical/mysql/compression_probe_test.go
@@ -0,0 +1,167 @@
+package usecases_logical_mysql
+
+import (
+ "log/slog"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/google/uuid"
+
+ mysqltypes "databasus-backend/internal/features/databases/databases/mysql"
+ "databasus-backend/internal/util/testing/containers"
+ "databasus-backend/internal/util/tools"
+)
+
+func Test_BuildMysqldumpArgs_ForEverySupportedVersion_OmitsCompressionFlags(t *testing.T) {
+ for _, version := range []tools.MysqlVersion{
+ tools.MysqlVersion57,
+ tools.MysqlVersion80,
+ tools.MysqlVersion84,
+ tools.MysqlVersion9,
+ } {
+ uc := &CreateMysqlBackupUsecase{}
+ database := &mysqltypes.MysqlDatabase{Version: version}
+
+ args := uc.buildMysqldumpArgs(database)
+
+ for _, arg := range args {
+ if strings.Contains(arg, "compress") {
+ t.Fatalf("compression is negotiated by the probe, not the arg builder; "+
+ "version %s produced %q", version, arg)
+ }
+ }
+ }
+}
+
+func Test_GetNetworkCompressionCandidates_OnMysql80AndNewer_TriesZstdThenZlibThenUncompressed(
+ t *testing.T,
+) {
+ for _, version := range []tools.MysqlVersion{
+ tools.MysqlVersion80,
+ tools.MysqlVersion84,
+ tools.MysqlVersion9,
+ } {
+ candidates := getNetworkCompressionCandidates(version)
+
+ if len(candidates) != 3 {
+ t.Fatalf("expected 3 candidates for %s, got %v", version, candidates)
+ }
+
+ if !slices.Contains(candidates[0], "--compression-algorithms=zstd") {
+ t.Fatalf("expected zstd first for %s, got %v", version, candidates[0])
+ }
+
+ if !slices.Contains(candidates[1], "--compression-algorithms=zlib") {
+ t.Fatalf("expected zlib second for %s, got %v", version, candidates[1])
+ }
+
+ if len(candidates[2]) != 0 {
+ t.Fatalf("expected uncompressed last for %s, got %v", version, candidates[2])
+ }
+ }
+}
+
+func Test_GetNetworkCompressionCandidates_OnMysql57_TriesCompressThenUncompressed(t *testing.T) {
+ candidates := getNetworkCompressionCandidates(tools.MysqlVersion57)
+
+ if len(candidates) != 2 {
+ t.Fatalf("expected 2 candidates, got %v", candidates)
+ }
+
+ if !slices.Equal(candidates[0], []string{"--compress"}) {
+ t.Fatalf("expected --compress first, got %v", candidates[0])
+ }
+
+ if len(candidates[1]) != 0 {
+ t.Fatalf("expected uncompressed last, got %v", candidates[1])
+ }
+}
+
+func Test_GetNetworkCompressionCandidates_OnMysql57_OmitsCompressionAlgorithms(t *testing.T) {
+ for _, candidate := range getNetworkCompressionCandidates(tools.MysqlVersion57) {
+ for _, arg := range candidate {
+ if strings.HasPrefix(arg, "--compression-algorithms") {
+ t.Fatalf("the 5.7 client has no --compression-algorithms, got %q", arg)
+ }
+ }
+ }
+}
+
+func Test_GetNetworkCompressionLabel_WhenCandidateIsEmpty_ReadsUncompressed(t *testing.T) {
+ if label := getNetworkCompressionLabel(nil); label != "uncompressed" {
+ t.Fatalf("expected \"uncompressed\", got %q", label)
+ }
+}
+
+func Test_IsCompressionRejection_OnError2066_ReportsRejection(t *testing.T) {
+ rejectionStderr := "mysqldump: Got error: 2066: Connection failed due to wrongly " +
+ "configured compression algorithm when trying to connect"
+
+ if !isCompressionRejection(rejectionStderr) {
+ t.Fatalf("expected error 2066 to read as a compression rejection, got %q", rejectionStderr)
+ }
+}
+
+func Test_IsCompressionRejection_OnUnrelatedFailure_ReportsNoRejection(t *testing.T) {
+ for _, unrelatedStderr := range []string{
+ "mysqldump: Got error: 1045: Access denied for user 'app'@'%' when trying to connect",
+ "mysqldump: Couldn't find table: \"__databasus_compression_probe__\"",
+ } {
+ if isCompressionRejection(unrelatedStderr) {
+ t.Fatalf("expected no compression rejection for %q", unrelatedStderr)
+ }
+ }
+}
+
+func probeCompressionAgainstMysql(t *testing.T, endpoint containers.Endpoint) []string {
+ t.Helper()
+
+ databaseName := containers.MysqlDatabase
+ database := &mysqltypes.MysqlDatabase{
+ Version: tools.MysqlVersion80,
+ Host: endpoint.Host,
+ Port: endpoint.Port,
+ Username: containers.MysqlUsername,
+ Database: &databaseName,
+ }
+ uc := &CreateMysqlBackupUsecase{logger: slog.New(slog.NewTextHandler(os.Stdout, nil))}
+
+ myCnfFile, err := uc.createTempMyCnfFile(database, containers.MysqlPassword)
+ if err != nil {
+ t.Fatalf("failed to create .my.cnf: %v", err)
+ }
+
+ t.Cleanup(func() { _ = os.RemoveAll(filepath.Dir(myCnfFile)) })
+
+ return uc.probeNetworkCompressionArgs(t.Context(), CompressionProbeSpec{
+ MysqldumpBin: tools.GetMysqlExecutable(
+ tools.MysqlVersion80, tools.MysqlExecutableMysqldump,
+ ),
+ MyCnfFile: myCnfFile,
+ DatabaseName: databaseName,
+ DatabaseID: uuid.New(),
+ }, tools.MysqlVersion80)
+}
+
+func Test_ProbeNetworkCompressionArgs_AgainstStockMysql80_SelectsZstd(t *testing.T) {
+ compressionArgs := probeCompressionAgainstMysql(t, containers.StartMysql(t, "mysql:8.0"))
+
+ if !slices.Contains(compressionArgs, "--compression-algorithms=zstd") {
+ t.Fatalf("expected zstd against a stock MySQL 8.0, got %v", compressionArgs)
+ }
+}
+
+func Test_ProbeNetworkCompressionArgs_WhenServerRefusesCompression_FallsBackToUncompressed(
+ t *testing.T,
+) {
+ compressionArgs := probeCompressionAgainstMysql(
+ t, containers.StartMysqlWithoutCompression(t, "mysql:8.0"),
+ )
+
+ if len(compressionArgs) != 0 {
+ t.Fatalf("expected the uncompressed fallback, got %v", compressionArgs)
+ }
+}
diff --git a/backend/internal/features/backups/backups/usecases/logical/mysql/create_backup_uc.go b/backend/internal/features/backups/backups/usecases/logical/mysql/create_backup_uc.go
index abdae4eb..9135d886 100644
--- a/backend/internal/features/backups/backups/usecases/logical/mysql/create_backup_uc.go
+++ b/backend/internal/features/backups/backups/usecases/logical/mysql/create_backup_uc.go
@@ -141,8 +141,6 @@ func (uc *CreateMysqlBackupUsecase) buildMysqldumpArgs(my *mysqltypes.MysqlDatab
}
}
- args = append(args, uc.getNetworkCompressionArgs(my)...)
-
args = append(args, "--max-allowed-packet=1G")
if my.IsHttps {
@@ -158,28 +156,6 @@ func (uc *CreateMysqlBackupUsecase) buildMysqldumpArgs(my *mysqltypes.MysqlDatab
return args
}
-func (uc *CreateMysqlBackupUsecase) getNetworkCompressionArgs(
- my *mysqltypes.MysqlDatabase,
-) []string {
- const zstdCompressionLevel = 5
-
- switch my.Version {
- case tools.MysqlVersion80, tools.MysqlVersion84, tools.MysqlVersion9:
- if my.IsZstdSupported {
- return []string{
- "--compression-algorithms=zstd",
- fmt.Sprintf("--zstd-compression-level=%d", zstdCompressionLevel),
- }
- }
-
- return []string{"--compress"}
- case tools.MysqlVersion57:
- return []string{"--compress"}
- default:
- return []string{"--compress"}
- }
-}
-
func (uc *CreateMysqlBackupUsecase) streamToStorage(
parentCtx context.Context,
backup *backups_core_logical.LogicalBackup,
@@ -202,7 +178,15 @@ func (uc *CreateMysqlBackupUsecase) streamToStorage(
}
defer func() { _ = os.RemoveAll(filepath.Dir(myCnfFile)) }()
- fullArgs := append([]string{"--defaults-file=" + myCnfFile}, args...)
+ compressionArgs := uc.probeNetworkCompressionArgs(ctx, CompressionProbeSpec{
+ MysqldumpBin: mysqlBin,
+ MyCnfFile: myCnfFile,
+ DatabaseName: *myConfig.Database,
+ DatabaseID: backup.DatabaseID,
+ }, myConfig.Version)
+
+ fullArgs := append([]string{"--defaults-file=" + myCnfFile}, compressionArgs...)
+ fullArgs = append(fullArgs, args...)
cmd := exec.CommandContext(ctx, mysqlBin, fullArgs...)
uc.logger.Info("Executing MySQL backup command", "command", cmd.String())
@@ -641,11 +625,11 @@ func (uc *CreateMysqlBackupUsecase) handleConnectionErrors(stderrStr string) err
)
}
- if containsIgnoreCase(stderrStr, "compression algorithm") ||
- containsIgnoreCase(stderrStr, "2066") {
+ if isCompressionRejection(stderrStr) {
return fmt.Errorf(
- "MySQL connection failed due to unsupported compression algorithm. "+
- "Try re-saving the database connection to re-detect compression support. stderr: %s",
+ "MySQL rejected the network compression algorithm that had just passed the "+
+ "pre-flight handshake probe. Compression is re-probed on every run, so retry "+
+ "the backup. stderr: %s",
stderrStr,
)
}
diff --git a/backend/internal/features/databases/databases/mysql/model.go b/backend/internal/features/databases/databases/mysql/model.go
index 414348a4..27e616f6 100644
--- a/backend/internal/features/databases/databases/mysql/model.go
+++ b/backend/internal/features/databases/databases/mysql/model.go
@@ -35,7 +35,6 @@ type MysqlDatabase struct {
ExcludeTables []string `json:"excludeTables" gorm:"-"`
ExcludeTablesString string `json:"-" gorm:"column:exclude_tables;type:text;not null;default:''"`
Privileges string `json:"privileges" gorm:"column:privileges;type:text;not null;default:''"`
- IsZstdSupported bool `json:"isZstdSupported" gorm:"column:is_zstd_supported;type:boolean;not null;default:true"`
IsUseExtendedInsert bool `json:"isUseExtendedInsert" gorm:"column:is_use_extended_insert;type:boolean;not null;default:false"`
}
@@ -126,7 +125,6 @@ func (m *MysqlDatabase) TestConnection(
return err
}
m.Privileges = privileges
- m.IsZstdSupported = detectZstdSupport(ctx, db)
if err := checkBackupPermissions(m.Privileges); err != nil {
return err
@@ -195,7 +193,6 @@ func (m *MysqlDatabase) Update(incoming *MysqlDatabase) {
m.IsHttps = incoming.IsHttps
m.ExcludeTables = incoming.ExcludeTables
m.Privileges = incoming.Privileges
- m.IsZstdSupported = incoming.IsZstdSupported
m.IsUseExtendedInsert = incoming.IsUseExtendedInsert
if incoming.Password != "" {
@@ -255,7 +252,6 @@ func (m *MysqlDatabase) PopulateDbData(
return err
}
m.Privileges = privileges
- m.IsZstdSupported = detectZstdSupport(ctx, db)
return nil
}
@@ -293,7 +289,6 @@ func (m *MysqlDatabase) PopulateVersion(
return err
}
m.Version = detectedVersion
- m.IsZstdSupported = detectZstdSupport(ctx, db)
return nil
}
@@ -689,22 +684,6 @@ func checkBackupPermissions(privileges string) error {
return nil
}
-// detectZstdSupport checks if the MySQL server supports zstd network compression.
-// The protocol_compression_algorithms variable was introduced in MySQL 8.0.18.
-// Managed MySQL providers (e.g. PlanetScale) may not support zstd even on 8.0+.
-func detectZstdSupport(ctx context.Context, db *sql.DB) bool {
- var varName, value string
-
- err := db.QueryRowContext(ctx,
- "SHOW VARIABLES LIKE 'protocol_compression_algorithms'",
- ).Scan(&varName, &value)
- if err != nil {
- return false
- }
-
- return strings.Contains(strings.ToLower(value), "zstd")
-}
-
func decryptPasswordIfNeeded(
password string,
encryptor encryption.FieldEncryptor,
diff --git a/backend/internal/features/databases/databases/mysql/model_test.go b/backend/internal/features/databases/databases/mysql/model_test.go
index ba132a02..5081a753 100644
--- a/backend/internal/features/databases/databases/mysql/model_test.go
+++ b/backend/internal/features/databases/databases/mysql/model_test.go
@@ -17,16 +17,15 @@ import (
)
type mysqlModelVersion struct {
- name string
- version tools.MysqlVersion
- image string
- supportsZstd bool
+ name string
+ version tools.MysqlVersion
+ image string
}
var mysqlModelVersions = []mysqlModelVersion{
- {"MySQL 5.7", tools.MysqlVersion57, "mysql:5.7", false},
- {"MySQL 8.0", tools.MysqlVersion80, "mysql:8.0", true},
- {"MySQL 8.4", tools.MysqlVersion84, "mysql:8.4", true},
+ {"MySQL 5.7", tools.MysqlVersion57, "mysql:5.7"},
+ {"MySQL 8.0", tools.MysqlVersion80, "mysql:8.0"},
+ {"MySQL 8.4", tools.MysqlVersion84, "mysql:8.4"},
}
// Test_MysqlModel_AcrossSupportedVersions boots each MySQL version once and runs every matrix model
@@ -44,10 +43,6 @@ func Test_MysqlModel_AcrossSupportedVersions(t *testing.T) {
testTestConnectionSufficientPermissions(t, endpoint, dbVersion.version)
})
- t.Run("Test_TestConnection_DetectsZstdSupport", func(t *testing.T) {
- testTestConnectionDetectsZstdSupport(t, endpoint, dbVersion.version, dbVersion.supportsZstd)
- })
-
t.Run("Test_IsUserReadOnly_AdminUser_ReturnsFalse", func(t *testing.T) {
testIsUserReadOnlyAdminUser(t, endpoint, dbVersion.version)
})
@@ -198,24 +193,6 @@ func testTestConnectionSufficientPermissions(
assert.NoError(t, err)
}
-func testTestConnectionDetectsZstdSupport(
- t *testing.T,
- endpoint containers.Endpoint,
- version tools.MysqlVersion,
- expectedZstd bool,
-) {
- container := connectToMysqlEndpoint(t, endpoint, version)
- defer container.DB.Close()
-
- mysqlModel := createMysqlModel(container)
- logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
-
- err := mysqlModel.TestConnection(logger, nil)
- assert.NoError(t, err)
- assert.Equal(t, expectedZstd, mysqlModel.IsZstdSupported,
- "IsZstdSupported mismatch")
-}
-
func testIsUserReadOnlyAdminUser(
t *testing.T,
endpoint containers.Endpoint,
@@ -870,16 +847,15 @@ func Test_ParseGrantPrivileges_ReturnsExpectedTokens(t *testing.T) {
func Test_HideSensitiveData_WhenCalled_ClearsPasswordAndPreservesOtherFields(t *testing.T) {
databaseName := "appdb"
mysqlModel := &MysqlDatabase{
- Version: tools.MysqlVersion80,
- Host: "db.example.com",
- Port: 3306,
- Username: "appuser",
- Password: "supersecret",
- Database: &databaseName,
- IsHttps: true,
- ExcludeTables: []string{"audit_logs"},
- Privileges: "SELECT, INSERT",
- IsZstdSupported: true,
+ Version: tools.MysqlVersion80,
+ Host: "db.example.com",
+ Port: 3306,
+ Username: "appuser",
+ Password: "supersecret",
+ Database: &databaseName,
+ IsHttps: true,
+ ExcludeTables: []string{"audit_logs"},
+ Privileges: "SELECT, INSERT",
}
mysqlModel.HideSensitiveData()
@@ -892,7 +868,6 @@ func Test_HideSensitiveData_WhenCalled_ClearsPasswordAndPreservesOtherFields(t *
assert.True(t, mysqlModel.IsHttps)
assert.Equal(t, []string{"audit_logs"}, mysqlModel.ExcludeTables)
assert.Equal(t, "SELECT, INSERT", mysqlModel.Privileges)
- assert.True(t, mysqlModel.IsZstdSupported)
}
func Test_HideSensitiveData_WhenReceiverIsNil_DoesNotPanic(t *testing.T) {
diff --git a/backend/internal/util/testing/containers/mysql.go b/backend/internal/util/testing/containers/mysql.go
index 78f0b247..24a11274 100644
--- a/backend/internal/util/testing/containers/mysql.go
+++ b/backend/internal/util/testing/containers/mysql.go
@@ -89,6 +89,17 @@ func StartMysql(t *testing.T, image string) Endpoint {
return start(t, mysqlRequest(image), mysqlPort)
}
+// StartMysqlWithoutCompression stands in for managed endpoints whose proxy cannot negotiate
+// compression even though the server advertises it (issue #687).
+func StartMysqlWithoutCompression(t *testing.T, image string) Endpoint {
+ t.Helper()
+
+ req := mysqlRequest(image)
+ req.Cmd = append(req.Cmd, "--protocol_compression_algorithms=uncompressed")
+
+ return start(t, req, mysqlPort)
+}
+
// StartMysqlSSL boots a MySQL server that rejects unencrypted connections. The image auto-generates
// its server certificates, so the test connects with tlsInsecure and no client cert.
func StartMysqlSSL(t *testing.T, image string) Endpoint {
diff --git a/backend/migrations/20260726073908_drop_is_zstd_supported_from_mysql.sql b/backend/migrations/20260726073908_drop_is_zstd_supported_from_mysql.sql
new file mode 100644
index 00000000..aec76b66
--- /dev/null
+++ b/backend/migrations/20260726073908_drop_is_zstd_supported_from_mysql.sql
@@ -0,0 +1,11 @@
+-- +goose Up
+-- +goose StatementBegin
+ALTER TABLE mysql_databases
+ DROP COLUMN IF EXISTS is_zstd_supported;
+-- +goose StatementEnd
+
+-- +goose Down
+-- +goose StatementBegin
+ALTER TABLE mysql_databases
+ ADD COLUMN IF NOT EXISTS is_zstd_supported BOOLEAN NOT NULL DEFAULT TRUE;
+-- +goose StatementEnd