Skip to content

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

FIX (backups): Route timeline history uploads through the file store

Rostislav Duginabeb0e3992c8
diff --git a/backend/internal/features/backups/backups/core/physical/repositories/wal_history_repository.go b/backend/internal/features/backups/backups/core/physical/repositories/wal_history_repository.go
index a15e4e7c..2a63f0a9 100644
--- a/backend/internal/features/backups/backups/core/physical/repositories/wal_history_repository.go
+++ b/backend/internal/features/backups/backups/core/physical/repositories/wal_history_repository.go
@@ -14,6 +14,15 @@ import (
type PhysicalWalHistoryRepository struct{}
func (r *PhysicalWalHistoryRepository) Insert(file *physical_models.PhysicalWalHistoryFile) error {
+ return r.InsertInTransaction(storage.GetDb(), file)
+}
+
+// InsertInTransaction lets the caller publish the history row and spend the write
+// receipts for its two files together.
+func (r *PhysicalWalHistoryRepository) InsertInTransaction(
+ tx *gorm.DB,
+ file *physical_models.PhysicalWalHistoryFile,
+) error {
if file.DatabaseID == uuid.Nil || file.StorageID == uuid.Nil {
return errors.New("database ID and storage ID are required")
}
@@ -21,11 +30,12 @@ func (r *PhysicalWalHistoryRepository) Insert(file *physical_models.PhysicalWalH
if file.ID == uuid.Nil {
file.ID = uuid.New()
}
+
if file.CreatedAt.IsZero() {
file.CreatedAt = time.Now().UTC()
}
- return storage.GetDb().Create(file).Error
+ return tx.Create(file).Error
}
func (r *PhysicalWalHistoryRepository) FindByDatabaseTimeline(
diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/create_full_uc.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/create_full_uc.go
index 5d9bad38..439d5c94 100644
--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/create_full_uc.go
+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/create_full_uc.go
@@ -157,19 +157,18 @@ func uploadHistoryForTimelineSwitch(ctx context.Context, common CommonBackupSpec
}
defer func() { _ = historyConn.Close(ctx) }()
- if _, err := UploadHistoryFile(
- ctx,
- historyConn,
- timelineID,
- common.Storage,
- common.SourceDB,
- common.StorageID,
- common.HistoryRepo,
- common.Encryption,
- common.MasterKey,
- common.FieldEncryptor,
- common.Logger,
- ); err != nil {
+ if _, err := UploadHistoryFile(ctx, HistoryUploadSpec{
+ Conn: historyConn,
+ TimelineID: timelineID,
+ FileStore: common.FileStore,
+ SourceDB: common.SourceDB,
+ StorageID: common.StorageID,
+ HistoryRepo: common.HistoryRepo,
+ Encryption: common.Encryption,
+ MasterKey: common.MasterKey,
+ FieldEncryptor: common.FieldEncryptor,
+ Logger: common.Logger,
+ }); err != nil {
common.Logger.Warn("history upload failed; FULL stays COMPLETED",
"timeline_id", timelineID,
"error", err)
diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/timeline.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/timeline.go
index 6f4c9263..2f6db23f 100644
--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/timeline.go
+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/timeline.go
@@ -14,6 +14,7 @@ import (
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/klauspost/compress/zstd"
+ "gorm.io/gorm"
backups_core_enums "databasus-backend/internal/features/backups/backups/core/enums"
chain_view "databasus-backend/internal/features/backups/backups/core/physical/chain_view"
@@ -22,7 +23,8 @@ import (
physical_repositories "databasus-backend/internal/features/backups/backups/core/physical/repositories"
backup_encryption "databasus-backend/internal/features/backups/backups/encryption"
postgresql_physical "databasus-backend/internal/features/databases/databases/postgresql/physical"
- "databasus-backend/internal/features/storages"
+ storage_files "databasus-backend/internal/features/storages/files"
+ db "databasus-backend/internal/storage"
util_encryption "databasus-backend/internal/util/encryption"
"databasus-backend/internal/util/walmath"
)
@@ -192,20 +194,34 @@ func ValidateStartLsnAgainstHistory(
//
// Shared by full.go (post-stream, when the FULL ran on a TL > 1) and
// PR 4's wal_stream.go (which also observes .history arrivals).
+// HistoryUploadSpec replaces an eleven-value positional list, which no call site
+// could read without counting.
+type HistoryUploadSpec struct {
+ Conn *pgx.Conn
+ TimelineID int
+ FileStore *storage_files.Store
+ SourceDB *postgresql_physical.PostgresqlPhysicalDatabase
+ StorageID uuid.UUID
+ HistoryRepo *physical_repositories.PhysicalWalHistoryRepository
+ Encryption backups_core_enums.BackupEncryption
+ MasterKey string
+ FieldEncryptor util_encryption.FieldEncryptor
+ Logger *slog.Logger
+}
+
func UploadHistoryFile(
ctx context.Context,
- conn *pgx.Conn,
- timelineID int,
- storage storages.StorageFileSaver,
- db *postgresql_physical.PostgresqlPhysicalDatabase,
- storageID uuid.UUID,
- historyRepo *physical_repositories.PhysicalWalHistoryRepository,
- encryption backups_core_enums.BackupEncryption,
- masterKey string,
- fieldEncryptor util_encryption.FieldEncryptor,
- logger *slog.Logger,
+ spec HistoryUploadSpec,
) (*physical_models.PhysicalWalHistoryFile, error) {
- databaseID := db.ParentDatabaseID()
+ conn := spec.Conn
+ timelineID := spec.TimelineID
+ historyRepo := spec.HistoryRepo
+ encryption := spec.Encryption
+ masterKey := spec.MasterKey
+ logger := spec.Logger
+ storageID := spec.StorageID
+
+ databaseID := spec.SourceDB.ParentDatabaseID()
existing, err := historyRepo.FindByDatabaseTimeline(databaseID, timelineID)
if err != nil {
@@ -228,7 +244,9 @@ func UploadHistoryFile(
}
historyFileID := uuid.New()
- storageObjectName := fmt.Sprintf("%s-HIST-tl%d.history.zst", databaseID, timelineID)
+ // The row's own identity is the per-attempt component: a retry for the same
+ // timeline writes a different object than the one a pending cleanup owns.
+ storageObjectName := fmt.Sprintf("%s-HIST-tl%d-%s.history.zst", databaseID, timelineID, historyFileID)
artifactReader, encryptionSalt, encryptionIV, err := buildHistoryArtifactReader(
body, encryption, masterKey, historyFileID,
@@ -237,7 +255,10 @@ func UploadHistoryFile(
return nil, err
}
- if err := storage.SaveFile(ctx, fieldEncryptor, logger, storageObjectName, artifactReader); err != nil {
+ artifactReference := storage_files.StoredFileReference{StorageID: storageID, FileName: storageObjectName}
+
+ artifactReceipt, err := spec.FileStore.WriteFile(ctx, artifactReference, artifactReader)
+ if err != nil {
return nil, fmt.Errorf("upload history artifact: %w", err)
}
@@ -262,16 +283,18 @@ func UploadHistoryFile(
return nil, fmt.Errorf("marshal history sidecar: %w", err)
}
- if err := storage.SaveFile(
- ctx, fieldEncryptor, logger, sidecarFilename, bytes.NewReader(sidecarBytes),
- ); err != nil {
- // Sidecar upload failed: remove the artifact to preserve the
- // "no artifact without sidecar" invariant. DeleteFile is
- // idempotent on not-found.
- if delErr := storage.DeleteFile(ctx, fieldEncryptor, logger, storageObjectName); delErr != nil {
- logger.WarnContext(ctx, "failed to remove orphan history artifact after sidecar failure",
+ sidecarReference := storage_files.StoredFileReference{StorageID: storageID, FileName: sidecarFilename}
+
+ sidecarReceipt, err := spec.FileStore.WriteFile(ctx, sidecarReference, bytes.NewReader(sidecarBytes))
+ if err != nil {
+ // An artifact with no sidecar cannot be restored from, so the attempt gives
+ // the artifact back rather than leaving half a history file behind.
+ if discardErr := spec.FileStore.RequestFileDeletions(
+ ctx, db.GetDb(), []storage_files.StoredFileReference{artifactReference},
+ ); discardErr != nil {
+ logger.WarnContext(ctx, "failed to discard a history artifact after its sidecar failed",
"file_name", storageObjectName,
- "error", delErr)
+ "error", discardErr)
}
return nil, fmt.Errorf("upload history sidecar: %w", err)
@@ -288,7 +311,16 @@ func UploadHistoryFile(
CreatedAt: sidecar.CreatedAt,
}
- if err := historyRepo.Insert(row); err != nil {
+ err = db.GetDb().Transaction(func(tx *gorm.DB) error {
+ if insertErr := historyRepo.InsertInTransaction(tx, row); insertErr != nil {
+ return insertErr
+ }
+
+ return spec.FileStore.ConfirmFileWrites(ctx, tx, []storage_files.WriteReceipt{
+ artifactReceipt, sidecarReceipt,
+ })
+ })
+ if err != nil {
if isUniqueViolation(err) {
logger.DebugContext(ctx, "history row inserted by concurrent caller",
"database_id", databaseID,
diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/timeline_history_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/timeline_history_test.go
index adaee29c..a416ca07 100644
--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/timeline_history_test.go
+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/timeline_history_test.go
@@ -66,19 +66,17 @@ func Test_UploadHistoryFile_KeysRowOnParentDatabaseID(t *testing.T) {
historyRepo := physical_repositories.GetWalHistoryRepository()
- row, err := UploadHistoryFile(
- t.Context(),
- conn,
- timelineID,
- newMockWalStorage(),
- sourceDB,
- fixture.Storage.ID,
- historyRepo,
- backups_core_enums.BackupEncryptionNone,
- "",
- encryption.GetFieldEncryptor(),
- logger.GetLogger(),
- )
+ row, err := UploadHistoryFile(t.Context(), HistoryUploadSpec{
+ Conn: conn,
+ TimelineID: timelineID,
+ FileStore: newMockWalStoreFor(newMockWalStorage()),
+ SourceDB: sourceDB,
+ StorageID: fixture.Storage.ID,
+ HistoryRepo: historyRepo,
+ Encryption: backups_core_enums.BackupEncryptionNone,
+ FieldEncryptor: encryption.GetFieldEncryptor(),
+ Logger: logger.GetLogger(),
+ })
require.NoError(t, err, "history insert must not violate fk_physical_wal_history_files_database_id")
require.NotNil(t, row)
t.Cleanup(func() { _ = historyRepo.DeleteByID(row.ID) })
diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_watch_dir.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_watch_dir.go
index e3fc3e66..075b38a1 100644
--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_watch_dir.go
+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_watch_dir.go
@@ -150,10 +150,18 @@ func (s *WalStreamSupervisor) archiveTimelineHistoryFile(ctx context.Context, lo
}
defer func() { _ = conn.Close(context.Background()) }()
- if _, err := UploadHistoryFile(
- ctx, conn, timelineID, s.spec.Storage, s.spec.SourceDB, s.spec.StorageID,
- s.spec.HistoryRepo, s.spec.Encryption, s.spec.MasterKey, s.spec.FieldEncryptor, logger,
- ); err != nil {
+ if _, err := UploadHistoryFile(ctx, HistoryUploadSpec{
+ Conn: conn,
+ TimelineID: timelineID,
+ FileStore: s.spec.FileStore,
+ SourceDB: s.spec.SourceDB,
+ StorageID: s.spec.StorageID,
+ HistoryRepo: s.spec.HistoryRepo,
+ Encryption: s.spec.Encryption,
+ MasterKey: s.spec.MasterKey,
+ FieldEncryptor: s.spec.FieldEncryptor,
+ Logger: logger,
+ }); err != nil {
logger.WarnContext(ctx, "history upload failed; will retry next tick", "timeline_id", timelineID, "error", err)
return