PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FIX (wal): Enforce streaming without RAM buffering over base backup
Rostislav Dugin29b403a9c648
diff --git a/AGENTS.md b/AGENTS.mdindex f931b0d7..79792594 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -73,6 +73,10 @@ This is NOT a strict set of rules, but a set of recommendations to help you writ- Patch the answer accordingly- Verify edge cases are handled+7. **Fix the reason, not the symptom:**+ - If you find a bug or issue, ask "Why did this happen?" and fix the root cause+ - Avoid quick fixes that don't address underlying problems+### Application guidelines:**Scale your response to the task:**@@ -88,6 +92,36 @@ This is NOT a strict set of rules, but a set of recommendations to help you writ## Backend guidelines+### Naming++Variables and functions naming are the most important part of code readability. Always choose descriptive and meaningful names that clearly indicate the purpose and intent of the code.++Avoid abbreviations, unless they are widely accepted and unambiguous (e.g., `ID`, `URL`, `HTTP`). Use consistent naming conventions across the codebase.++Do not use one-two letters. For example:++Bad:++```+ u := users.getUser()++ pr, pw := io.Pipe()++ r := bufio.NewReader(pr)+```++Good:++```+ user := users.GetUser()++ pipeReader, pipeWriter := io.Pipe()++ bufferedReader := bufio.NewReader(pipeReader)+```++Exclusion: widely used variables like "db", "ctx", "req", "res", etc.+### Code style**Always place private methods to the bottom of file**diff --git a/agent/internal/features/api/api.go b/agent/internal/features/api/api.goindex 322a619b..d217fb84 100644--- a/agent/internal/features/api/api.go+++ b/agent/internal/features/api/api.go@@ -16,7 +16,9 @@ import (const (chainValidPath = "/api/v1/backups/postgres/wal/is-wal-chain-valid-since-last-full-backup"nextBackupTimePath = "/api/v1/backups/postgres/wal/next-full-backup-time"- uploadPath = "/api/v1/backups/postgres/wal/upload"+ walUploadPath = "/api/v1/backups/postgres/wal/upload/wal"+ fullStartPath = "/api/v1/backups/postgres/wal/upload/full-start"+ fullCompletePath = "/api/v1/backups/postgres/wal/upload/full-complete"reportErrorPath = "/api/v1/backups/postgres/wal/error"versionPath = "/api/v1/system/version"agentBinaryPath = "/api/v1/system/agent"@@ -102,30 +104,76 @@ func (c *Client) ReportBackupError(ctx context.Context, errMsg string) error {func (c *Client) UploadBasebackup(ctx context.Context,- startSegment string,- stopSegment string,body io.Reader,-) error {- url := fmt.Sprintf("%s?fullBackupWalStartSegment=%s&fullBackupWalStopSegment=%s",- c.buildURL(uploadPath), startSegment, stopSegment,- )-+) (*UploadBasebackupResponse, error) {resp, err := c.stream.R().SetContext(ctx).SetBody(body).SetHeader("Content-Type", "application/octet-stream").- SetHeader("X-Upload-Type", "basebackup").SetDoNotParseResponse(true).- Post(url)+ Post(c.buildURL(fullStartPath))if err != nil {- return fmt.Errorf("upload request: %w", err)+ return nil, fmt.Errorf("upload request: %w", err)}defer func() { _ = resp.RawBody().Close() }()- if resp.StatusCode() != http.StatusNoContent {+ if resp.StatusCode() != http.StatusOK {respBody, _ := io.ReadAll(resp.RawBody())- return fmt.Errorf("upload failed with status %d: %s", resp.StatusCode(), string(respBody))+ return nil, fmt.Errorf("upload failed with status %d: %s", resp.StatusCode(), string(respBody))+ }++ var result UploadBasebackupResponse+ if err := json.NewDecoder(resp.RawBody()).Decode(&result); err != nil {+ return nil, fmt.Errorf("decode upload response: %w", err)+ }++ return &result, nil+}++func (c *Client) FinalizeBasebackup(+ ctx context.Context,+ backupID string,+ startSegment string,+ stopSegment string,+) error {+ resp, err := c.json.R().+ SetContext(ctx).+ SetBody(finalizeBasebackupRequest{+ BackupID: backupID,+ StartSegment: startSegment,+ StopSegment: stopSegment,+ }).+ Post(c.buildURL(fullCompletePath))+ if err != nil {+ return fmt.Errorf("finalize request: %w", err)+ }++ if resp.StatusCode() != http.StatusOK {+ return fmt.Errorf("finalize failed with status %d: %s", resp.StatusCode(), resp.String())+ }++ return nil+}++func (c *Client) FinalizeBasebackupWithError(+ ctx context.Context,+ backupID string,+ errMsg string,+) error {+ resp, err := c.json.R().+ SetContext(ctx).+ SetBody(finalizeBasebackupRequest{+ BackupID: backupID,+ Error: &errMsg,+ }).+ Post(c.buildURL(fullCompletePath))+ if err != nil {+ return fmt.Errorf("finalize-with-error request: %w", err)+ }++ if resp.StatusCode() != http.StatusOK {+ return fmt.Errorf("finalize-with-error failed with status %d: %s", resp.StatusCode(), resp.String())}return nil@@ -140,10 +188,9 @@ func (c *Client) UploadWalSegment(SetContext(ctx).SetBody(body).SetHeader("Content-Type", "application/octet-stream").- SetHeader("X-Upload-Type", "wal").SetHeader("X-Wal-Segment-Name", segmentName).SetDoNotParseResponse(true).- Post(c.buildURL(uploadPath))+ Post(c.buildURL(walUploadPath))if err != nil {return nil, fmt.Errorf("upload request: %w", err)}diff --git a/agent/internal/features/api/dto.go b/agent/internal/features/api/dto.goindex 2a729cdc..3495b969 100644--- a/agent/internal/features/api/dto.go+++ b/agent/internal/features/api/dto.go@@ -26,6 +26,17 @@ type versionResponse struct {Version string `json:"version"`}+type UploadBasebackupResponse struct {+ BackupID string `json:"backupId"`+}++type finalizeBasebackupRequest struct {+ BackupID string `json:"backupId"`+ StartSegment string `json:"startSegment"`+ StopSegment string `json:"stopSegment"`+ Error *string `json:"error,omitempty"`+}+type uploadErrorResponse struct {Error string `json:"error"`ExpectedSegmentName string `json:"expectedSegmentName"`diff --git a/agent/internal/features/full_backup/backuper.go b/agent/internal/features/full_backup/backuper.goindex f60a9c4b..478809ed 100644--- a/agent/internal/features/full_backup/backuper.go+++ b/agent/internal/features/full_backup/backuper.go@@ -173,61 +173,75 @@ func (backuper *FullBackuper) executeAndUploadBasebackup(ctx context.Context) erreturn fmt.Errorf("start pg_basebackup: %w", err)}- var compressedBuf bytes.Buffer- compressErr := backuper.compressToBuffer(&compressedBuf, stdoutPipe)+ // Phase 1: Stream compressed data via io.Pipe directly to the API.+ pipeReader, pipeWriter := io.Pipe()+ go backuper.compressAndStream(pipeWriter, stdoutPipe)++ uploadCtx, cancel := context.WithTimeout(ctx, uploadTimeout)+ defer cancel()++ uploadResp, uploadErr := backuper.apiClient.UploadBasebackup(uploadCtx, pipeReader)cmdErr := cmd.Wait()- if cmdErr != nil {- return fmt.Errorf("pg_basebackup exited with error: %w (stderr: %s)", cmdErr, stderrBuf.String())++ if uploadErr != nil {+ return fmt.Errorf("upload basebackup: %w", uploadErr)}- if compressErr != nil {- return fmt.Errorf("compress basebackup: %w", compressErr)+ if cmdErr != nil {+ errMsg := fmt.Sprintf("pg_basebackup exited with error: %v (stderr: %s)", cmdErr, stderrBuf.String())+ _ = backuper.apiClient.FinalizeBasebackupWithError(ctx, uploadResp.BackupID, errMsg)++ return fmt.Errorf("pg_basebackup: %w", cmdErr)}+ // Phase 2: Parse stderr for WAL segments and finalize the backup.stderrStr := stderrBuf.String()backuper.log.Debug("pg_basebackup stderr", "stderr", stderrStr)startSegment, stopSegment, err := ParseBasebackupStderr(stderrStr)if err != nil {+ errMsg := fmt.Sprintf("parse pg_basebackup stderr: %v", err)+ _ = backuper.apiClient.FinalizeBasebackupWithError(ctx, uploadResp.BackupID, errMsg)+return fmt.Errorf("parse pg_basebackup stderr: %w", err)}backuper.log.Info("Basebackup WAL segments parsed","startSegment", startSegment,"stopSegment", stopSegment,- "compressedSize", compressedBuf.Len(),+ "backupId", uploadResp.BackupID,)- uploadCtx, cancel := context.WithTimeout(ctx, uploadTimeout)- defer cancel()-- if err := backuper.apiClient.UploadBasebackup(uploadCtx, startSegment, stopSegment, &compressedBuf); err != nil {- return fmt.Errorf("upload basebackup: %w", err)+ if err := backuper.apiClient.FinalizeBasebackup(ctx, uploadResp.BackupID, startSegment, stopSegment); err != nil {+ return fmt.Errorf("finalize basebackup: %w", err)}return nil}-func (backuper *FullBackuper) compressToBuffer(dst *bytes.Buffer, reader io.Reader) error {- encoder, err := zstd.NewWriter(dst,- zstd.WithEncoderLevel(zstd.EncoderLevel(5)),+func (backuper *FullBackuper) compressAndStream(pipeWriter *io.PipeWriter, reader io.Reader) {+ encoder, err := zstd.NewWriter(pipeWriter,+ zstd.WithEncoderLevel(zstd.EncoderLevelFromZstd(5)),zstd.WithEncoderCRC(true),)if err != nil {- return fmt.Errorf("create zstd encoder: %w", err)+ _ = pipeWriter.CloseWithError(fmt.Errorf("create zstd encoder: %w", err))+ return}if _, err := io.Copy(encoder, reader); err != nil {_ = encoder.Close()- return fmt.Errorf("compress: %w", err)+ _ = pipeWriter.CloseWithError(fmt.Errorf("compress: %w", err))+ return}if err := encoder.Close(); err != nil {- return fmt.Errorf("close encoder: %w", err)+ _ = pipeWriter.CloseWithError(fmt.Errorf("close encoder: %w", err))+ return}- return nil+ _ = pipeWriter.Close()}func (backuper *FullBackuper) reportError(ctx context.Context, errMsg string) {diff --git a/agent/internal/features/full_backup/backuper_test.go b/agent/internal/features/full_backup/backuper_test.goindex 1c8350f7..eb9bee77 100644--- a/agent/internal/features/full_backup/backuper_test.go+++ b/agent/internal/features/full_backup/backuper_test.go@@ -26,15 +26,19 @@ import (const (testChainValidPath = "/api/v1/backups/postgres/wal/is-wal-chain-valid-since-last-full-backup"testNextBackupTimePath = "/api/v1/backups/postgres/wal/next-full-backup-time"- testUploadPath = "/api/v1/backups/postgres/wal/upload"+ testFullStartPath = "/api/v1/backups/postgres/wal/upload/full-start"+ testFullCompletePath = "/api/v1/backups/postgres/wal/upload/full-complete"testReportErrorPath = "/api/v1/backups/postgres/wal/error"++ testBackupID = "test-backup-id-1234")func Test_RunFullBackup_WhenChainBroken_BasebackupTriggered(t *testing.T) {var mu sync.Mutexvar uploadReceived boolvar uploadHeaders http.Header- var uploadQuery string+ var finalizeReceived bool+ var finalizeBody map[string]anyserver := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {switch r.URL.Path {@@ -44,15 +48,21 @@ func Test_RunFullBackup_WhenChainBroken_BasebackupTriggered(t *testing.T) {Error: "wal_chain_broken",LastContiguousSegment: "000000010000000100000011",})- case testUploadPath:+ case testFullStartPath:mu.Lock()uploadReceived = trueuploadHeaders = r.Header.Clone()- uploadQuery = r.URL.RawQuerymu.Unlock()_, _ = io.ReadAll(r.Body)- w.WriteHeader(http.StatusNoContent)+ writeJSON(w, map[string]string{"backupId": testBackupID})+ case testFullCompletePath:+ mu.Lock()+ finalizeReceived = true+ _ = json.NewDecoder(r.Body).Decode(&finalizeBody)+ mu.Unlock()++ w.WriteHeader(http.StatusOK)default:w.WriteHeader(http.StatusNotFound)}@@ -68,7 +78,7 @@ func Test_RunFullBackup_WhenChainBroken_BasebackupTriggered(t *testing.T) {waitForCondition(t, func() bool {mu.Lock()defer mu.Unlock()- return uploadReceived+ return finalizeReceived}, 5*time.Second)cancel()@@ -76,16 +86,18 @@ func Test_RunFullBackup_WhenChainBroken_BasebackupTriggered(t *testing.T) {defer mu.Unlock()assert.True(t, uploadReceived)- assert.Equal(t, "basebackup", uploadHeaders.Get("X-Upload-Type"))assert.Equal(t, "application/octet-stream", uploadHeaders.Get("Content-Type"))assert.Equal(t, "test-token", uploadHeaders.Get("Authorization"))- assert.Contains(t, uploadQuery, "fullBackupWalStartSegment=000000010000000000000002")- assert.Contains(t, uploadQuery, "fullBackupWalStopSegment=000000010000000000000002")++ assert.True(t, finalizeReceived)+ assert.Equal(t, testBackupID, finalizeBody["backupId"])+ assert.Equal(t, "000000010000000000000002", finalizeBody["startSegment"])+ assert.Equal(t, "000000010000000000000002", finalizeBody["stopSegment"])}func Test_RunFullBackup_WhenScheduledBackupDue_BasebackupTriggered(t *testing.T) {var mu sync.Mutex- var uploadReceived bool+ var finalizeReceived boolpastTime := time.Now().UTC().Add(-1 * time.Hour)@@ -95,13 +107,15 @@ func Test_RunFullBackup_WhenScheduledBackupDue_BasebackupTriggered(t *testing.T)writeJSON(w, api.WalChainValidityResponse{IsValid: true})case testNextBackupTimePath:writeJSON(w, api.NextFullBackupTimeResponse{NextFullBackupTime: &pastTime})- case testUploadPath:+ case testFullStartPath:+ _, _ = io.ReadAll(r.Body)+ writeJSON(w, map[string]string{"backupId": testBackupID})+ case testFullCompletePath:mu.Lock()- uploadReceived = true+ finalizeReceived = truemu.Unlock()- _, _ = io.ReadAll(r.Body)- w.WriteHeader(http.StatusNoContent)+ w.WriteHeader(http.StatusOK)default:w.WriteHeader(http.StatusNotFound)}@@ -117,19 +131,19 @@ func Test_RunFullBackup_WhenScheduledBackupDue_BasebackupTriggered(t *testing.T)waitForCondition(t, func() bool {mu.Lock()defer mu.Unlock()- return uploadReceived+ return finalizeReceived}, 5*time.Second)cancel()mu.Lock()defer mu.Unlock()- assert.True(t, uploadReceived)+ assert.True(t, finalizeReceived)}func Test_RunFullBackup_WhenNoFullBackupExists_ImmediateBasebackupTriggered(t *testing.T) {var mu sync.Mutex- var uploadReceived bool+ var finalizeReceived boolserver := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {switch r.URL.Path {@@ -138,13 +152,15 @@ func Test_RunFullBackup_WhenNoFullBackupExists_ImmediateBasebackupTriggered(t *tIsValid: false,Error: "no_full_backup",})- case testUploadPath:+ case testFullStartPath:+ _, _ = io.ReadAll(r.Body)+ writeJSON(w, map[string]string{"backupId": testBackupID})+ case testFullCompletePath:mu.Lock()- uploadReceived = true+ finalizeReceived = truemu.Unlock()- _, _ = io.ReadAll(r.Body)- w.WriteHeader(http.StatusNoContent)+ w.WriteHeader(http.StatusOK)default:w.WriteHeader(http.StatusNotFound)}@@ -160,14 +176,14 @@ func Test_RunFullBackup_WhenNoFullBackupExists_ImmediateBasebackupTriggered(t *twaitForCondition(t, func() bool {mu.Lock()defer mu.Unlock()- return uploadReceived+ return finalizeReceived}, 5*time.Second)cancel()mu.Lock()defer mu.Unlock()- assert.True(t, uploadReceived)+ assert.True(t, finalizeReceived)}func Test_RunFullBackup_WhenUploadFails_RetriesAfterDelay(t *testing.T) {@@ -182,7 +198,7 @@ func Test_RunFullBackup_WhenUploadFails_RetriesAfterDelay(t *testing.T) {IsValid: false,Error: "no_full_backup",})- case testUploadPath:+ case testFullStartPath:_, _ = io.ReadAll(r.Body)mu.Lock()@@ -196,7 +212,9 @@ func Test_RunFullBackup_WhenUploadFails_RetriesAfterDelay(t *testing.T) {return}- w.WriteHeader(http.StatusNoContent)+ writeJSON(w, map[string]string{"backupId": testBackupID})+ case testFullCompletePath:+ w.WriteHeader(http.StatusOK)case testReportErrorPath:mu.Lock()errorReported = true@@ -244,14 +262,16 @@ func Test_RunFullBackup_WhenAlreadyRunning_SkipsExecution(t *testing.T) {IsValid: false,Error: "no_full_backup",})- case testUploadPath:+ case testFullStartPath:_, _ = io.ReadAll(r.Body)mu.Lock()uploadCount++mu.Unlock()- w.WriteHeader(http.StatusNoContent)+ writeJSON(w, map[string]string{"backupId": testBackupID})+ case testFullCompletePath:+ w.WriteHeader(http.StatusOK)default:w.WriteHeader(http.StatusNotFound)}@@ -279,9 +299,11 @@ func Test_RunFullBackup_WhenContextCancelled_StopsCleanly(t *testing.T) {IsValid: false,Error: "no_full_backup",})- case testUploadPath:+ case testFullStartPath:_, _ = io.ReadAll(r.Body)w.WriteHeader(http.StatusInternalServerError)+ case testFullCompletePath:+ w.WriteHeader(http.StatusOK)case testReportErrorPath:w.WriteHeader(http.StatusOK)default:@@ -323,11 +345,13 @@ func Test_RunFullBackup_WhenChainValidAndNotScheduled_NoBasebackupTriggered(t *twriteJSON(w, api.WalChainValidityResponse{IsValid: true})case testNextBackupTimePath:writeJSON(w, api.NextFullBackupTimeResponse{NextFullBackupTime: &futureTime})- case testUploadPath:+ case testFullStartPath:uploadReceived.Store(true)_, _ = io.ReadAll(r.Body)- w.WriteHeader(http.StatusNoContent)+ writeJSON(w, map[string]string{"backupId": testBackupID})+ case testFullCompletePath:+ w.WriteHeader(http.StatusOK)default:w.WriteHeader(http.StatusNotFound)}@@ -346,10 +370,11 @@ func Test_RunFullBackup_WhenChainValidAndNotScheduled_NoBasebackupTriggered(t *tassert.False(t, uploadReceived.Load(), "should not trigger backup when chain valid and not scheduled")}-func Test_RunFullBackup_WhenStderrParsingFails_ReportsErrorAndRetries(t *testing.T) {+func Test_RunFullBackup_WhenStderrParsingFails_FinalizesWithErrorAndRetries(t *testing.T) {var mu sync.Mutexvar errorReported bool- var uploadAttempts int+ var finalizeWithErrorReceived bool+ var finalizeBody map[string]interface{}server := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {switch r.URL.Path {@@ -358,13 +383,16 @@ func Test_RunFullBackup_WhenStderrParsingFails_ReportsErrorAndRetries(t *testingIsValid: false,Error: "no_full_backup",})- case testUploadPath:+ case testFullStartPath:+ _, _ = io.ReadAll(r.Body)+ writeJSON(w, map[string]string{"backupId": testBackupID})+ case testFullCompletePath:mu.Lock()- uploadAttempts+++ finalizeWithErrorReceived = true+ _ = json.NewDecoder(r.Body).Decode(&finalizeBody)mu.Unlock()- _, _ = io.ReadAll(r.Body)- w.WriteHeader(http.StatusNoContent)+ w.WriteHeader(http.StatusOK)case testReportErrorPath:mu.Lock()errorReported = true@@ -398,12 +426,14 @@ func Test_RunFullBackup_WhenStderrParsingFails_ReportsErrorAndRetries(t *testingdefer mu.Unlock()assert.True(t, errorReported)- assert.Equal(t, 0, uploadAttempts, "should not upload when stderr parsing fails")+ assert.True(t, finalizeWithErrorReceived, "should finalize with error when stderr parsing fails")+ assert.Equal(t, testBackupID, finalizeBody["backupId"])+ assert.NotNil(t, finalizeBody["error"], "finalize should include error message")}func Test_RunFullBackup_WhenNextBackupTimeNull_BasebackupTriggered(t *testing.T) {var mu sync.Mutex- var uploadReceived bool+ var finalizeReceived boolserver := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {switch r.URL.Path {@@ -411,13 +441,15 @@ func Test_RunFullBackup_WhenNextBackupTimeNull_BasebackupTriggered(t *testing.T)writeJSON(w, api.WalChainValidityResponse{IsValid: true})case testNextBackupTimePath:writeJSON(w, api.NextFullBackupTimeResponse{NextFullBackupTime: nil})- case testUploadPath:+ case testFullStartPath:+ _, _ = io.ReadAll(r.Body)+ writeJSON(w, map[string]string{"backupId": testBackupID})+ case testFullCompletePath:mu.Lock()- uploadReceived = true+ finalizeReceived = truemu.Unlock()- _, _ = io.ReadAll(r.Body)- w.WriteHeader(http.StatusNoContent)+ w.WriteHeader(http.StatusOK)default:w.WriteHeader(http.StatusNotFound)}@@ -433,14 +465,14 @@ func Test_RunFullBackup_WhenNextBackupTimeNull_BasebackupTriggered(t *testing.T)waitForCondition(t, func() bool {mu.Lock()defer mu.Unlock()- return uploadReceived+ return finalizeReceived}, 5*time.Second)cancel()mu.Lock()defer mu.Unlock()- assert.True(t, uploadReceived)+ assert.True(t, finalizeReceived)}func Test_RunFullBackup_WhenUploadSucceeds_BodyIsZstdCompressed(t *testing.T) {@@ -454,14 +486,16 @@ func Test_RunFullBackup_WhenUploadSucceeds_BodyIsZstdCompressed(t *testing.T) {IsValid: false,Error: "no_full_backup",})- case testUploadPath:+ case testFullStartPath:body, _ := io.ReadAll(r.Body)mu.Lock()receivedBody = bodymu.Unlock()- w.WriteHeader(http.StatusNoContent)+ writeJSON(w, map[string]string{"backupId": testBackupID})+ case testFullCompletePath:+ w.WriteHeader(http.StatusOK)default:w.WriteHeader(http.StatusNotFound)}diff --git a/agent/internal/features/wal/streamer.go b/agent/internal/features/wal/streamer.goindex 7db24cba..c1513fda 100644--- a/agent/internal/features/wal/streamer.go+++ b/agent/internal/features/wal/streamer.go@@ -159,7 +159,7 @@ func (s *Streamer) compressAndStream(pw *io.PipeWriter, filePath string) {defer func() { _ = f.Close() }()encoder, err := zstd.NewWriter(pw,- zstd.WithEncoderLevel(zstd.EncoderLevel(5)),+ zstd.WithEncoderLevel(zstd.EncoderLevelFromZstd(5)),zstd.WithEncoderCRC(true),)if err != nil {diff --git a/backend/internal/features/backups/backups/backuping/cleaner.go b/backend/internal/features/backups/backups/backuping/cleaner.goindex 44c3c1b5..15880914 100644--- a/backend/internal/features/backups/backups/backuping/cleaner.go+++ b/backend/internal/features/backups/backups/backuping/cleaner.go@@ -59,6 +59,10 @@ func (c *BackupCleaner) Run(ctx context.Context) {if err := c.cleanExceededBackups(); err != nil {c.logger.Error("Failed to clean exceeded backups", "error", err)}++ if err := c.cleanStaleUploadedBasebackups(); err != nil {+ c.logger.Error("Failed to clean stale uploaded basebackups", "error", err)+ }}}})@@ -100,6 +104,38 @@ func (c *BackupCleaner) AddBackupRemoveListener(listener backups_core.BackupRemoc.backupRemoveListeners = append(c.backupRemoveListeners, listener)}+func (c *BackupCleaner) cleanStaleUploadedBasebackups() error {+ staleBackups, err := c.backupRepository.FindStaleUploadedBasebackups(+ time.Now().UTC().Add(-10 * time.Minute),+ )+ if err != nil {+ return fmt.Errorf("failed to find stale uploaded basebackups: %w", err)+ }++ for _, backup := range staleBackups {+ failMsg := "basebackup finalization timed out after 10 minutes"+ backup.Status = backups_core.BackupStatusFailed+ backup.FailMessage = &failMsg++ if err := c.backupRepository.Save(backup); err != nil {+ c.logger.Error(+ "Failed to mark stale uploaded basebackup as failed",+ "backupId", backup.ID,+ "error", err,+ )+ continue+ }++ c.logger.Info(+ "Marked stale uploaded basebackup as failed",+ "backupId", backup.ID,+ "databaseId", backup.DatabaseID,+ )+ }++ return nil+}+func (c *BackupCleaner) cleanByRetentionPolicy() error {enabledBackupConfigs, err := c.backupConfigService.GetBackupConfigsWithEnabledBackups()if err != nil {diff --git a/backend/internal/features/backups/backups/backuping/cleaner_test.go b/backend/internal/features/backups/backups/backuping/cleaner_test.goindex c8995dd8..a6d22e24 100644--- a/backend/internal/features/backups/backups/backuping/cleaner_test.go+++ b/backend/internal/features/backups/backups/backuping/cleaner_test.go@@ -1004,6 +1004,142 @@ func (m *mockBackupRemoveListener) OnBeforeBackupRemove(backup *backups_core.Bacreturn nil}+func Test_CleanStaleUploadedBasebackups_MarksAsFailed(t *testing.T) {+ router := CreateTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)+ storage := storages.CreateTestStorage(workspace.ID)+ notifier := notifiers.CreateTestNotifier(workspace.ID)+ database := databases.CreateTestDatabase(workspace.ID, storage, notifier)++ defer func() {+ backups, _ := backupRepository.FindByDatabaseID(database.ID)+ for _, backup := range backups {+ backupRepository.DeleteByID(backup.ID)+ }++ databases.RemoveTestDatabase(database)+ time.Sleep(50 * time.Millisecond)+ notifiers.RemoveTestNotifier(notifier)+ storages.RemoveTestStorage(storage.ID)+ workspaces_testing.RemoveTestWorkspace(workspace, router)+ }()++ staleTime := time.Now().UTC().Add(-15 * time.Minute)+ walBackupType := backups_core.PgWalBackupTypeFullBackup+ staleBackup := &backups_core.Backup{+ ID: uuid.New(),+ DatabaseID: database.ID,+ StorageID: storage.ID,+ Status: backups_core.BackupStatusInProgress,+ PgWalBackupType: &walBackupType,+ UploadCompletedAt: &staleTime,+ CreatedAt: staleTime,+ }++ err := backupRepository.Save(staleBackup)+ assert.NoError(t, err)++ cleaner := GetBackupCleaner()+ err = cleaner.cleanStaleUploadedBasebackups()+ assert.NoError(t, err)++ updated, err := backupRepository.FindByID(staleBackup.ID)+ assert.NoError(t, err)+ assert.Equal(t, backups_core.BackupStatusFailed, updated.Status)+ assert.NotNil(t, updated.FailMessage)+ assert.Contains(t, *updated.FailMessage, "finalization timed out")+}++func Test_CleanStaleUploadedBasebackups_SkipsRecentUploads(t *testing.T) {+ router := CreateTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)+ storage := storages.CreateTestStorage(workspace.ID)+ notifier := notifiers.CreateTestNotifier(workspace.ID)+ database := databases.CreateTestDatabase(workspace.ID, storage, notifier)++ defer func() {+ backups, _ := backupRepository.FindByDatabaseID(database.ID)+ for _, backup := range backups {+ backupRepository.DeleteByID(backup.ID)+ }++ databases.RemoveTestDatabase(database)+ time.Sleep(50 * time.Millisecond)+ notifiers.RemoveTestNotifier(notifier)+ storages.RemoveTestStorage(storage.ID)+ workspaces_testing.RemoveTestWorkspace(workspace, router)+ }()++ recentTime := time.Now().UTC().Add(-2 * time.Minute)+ walBackupType := backups_core.PgWalBackupTypeFullBackup+ recentBackup := &backups_core.Backup{+ ID: uuid.New(),+ DatabaseID: database.ID,+ StorageID: storage.ID,+ Status: backups_core.BackupStatusInProgress,+ PgWalBackupType: &walBackupType,+ UploadCompletedAt: &recentTime,+ CreatedAt: recentTime,+ }++ err := backupRepository.Save(recentBackup)+ assert.NoError(t, err)++ cleaner := GetBackupCleaner()+ err = cleaner.cleanStaleUploadedBasebackups()+ assert.NoError(t, err)++ updated, err := backupRepository.FindByID(recentBackup.ID)+ assert.NoError(t, err)+ assert.Equal(t, backups_core.BackupStatusInProgress, updated.Status)+}++func Test_CleanStaleUploadedBasebackups_SkipsActiveStreaming(t *testing.T) {+ router := CreateTestRouter()+ owner := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Test Workspace", owner, router)+ storage := storages.CreateTestStorage(workspace.ID)+ notifier := notifiers.CreateTestNotifier(workspace.ID)+ database := databases.CreateTestDatabase(workspace.ID, storage, notifier)++ defer func() {+ backups, _ := backupRepository.FindByDatabaseID(database.ID)+ for _, backup := range backups {+ backupRepository.DeleteByID(backup.ID)+ }++ databases.RemoveTestDatabase(database)+ time.Sleep(50 * time.Millisecond)+ notifiers.RemoveTestNotifier(notifier)+ storages.RemoveTestStorage(storage.ID)+ workspaces_testing.RemoveTestWorkspace(workspace, router)+ }()++ walBackupType := backups_core.PgWalBackupTypeFullBackup+ activeBackup := &backups_core.Backup{+ ID: uuid.New(),+ DatabaseID: database.ID,+ StorageID: storage.ID,+ Status: backups_core.BackupStatusInProgress,+ PgWalBackupType: &walBackupType,+ CreatedAt: time.Now().UTC().Add(-30 * time.Minute),+ }++ err := backupRepository.Save(activeBackup)+ assert.NoError(t, err)++ cleaner := GetBackupCleaner()+ err = cleaner.cleanStaleUploadedBasebackups()+ assert.NoError(t, err)++ updated, err := backupRepository.FindByID(activeBackup.ID)+ assert.NoError(t, err)+ assert.Equal(t, backups_core.BackupStatusInProgress, updated.Status)+ assert.Nil(t, updated.UploadCompletedAt)+}+func createTestInterval() *intervals.Interval {timeOfDay := "04:00"interval := &intervals.Interval{diff --git a/backend/internal/features/backups/backups/controllers/postgres_wal_controller.go b/backend/internal/features/backups/backups/controllers/postgres_wal_controller.goindex fca0b5a9..5888651e 100644--- a/backend/internal/features/backups/backups/controllers/postgres_wal_controller.go+++ b/backend/internal/features/backups/backups/controllers/postgres_wal_controller.go@@ -7,7 +7,6 @@ import ("github.com/gin-gonic/gin""github.com/google/uuid"- backups_core "databasus-backend/internal/features/backups/backups/core"backups_dto "databasus-backend/internal/features/backups/backups/dto"backups_services "databasus-backend/internal/features/backups/backups/services""databasus-backend/internal/features/databases"@@ -26,7 +25,9 @@ func (c *PostgreWalBackupController) RegisterRoutes(router *gin.RouterGroup) {walRoutes.GET("/next-full-backup-time", c.GetNextFullBackupTime)walRoutes.GET("/is-wal-chain-valid-since-last-full-backup", c.IsWalChainValidSinceLastBackup)walRoutes.POST("/error", c.ReportError)- walRoutes.POST("/upload", c.Upload)+ walRoutes.POST("/upload/wal", c.UploadWalSegment)+ walRoutes.POST("/upload/full-start", c.StartFullBackupUpload)+ walRoutes.POST("/upload/full-complete", c.CompleteFullBackupUpload)walRoutes.GET("/restore/plan", c.GetRestorePlan)walRoutes.GET("/restore/download", c.DownloadBackupFile)}@@ -117,73 +118,72 @@ func (c *PostgreWalBackupController) IsWalChainValidSinceLastBackup(ctx *gin.Conctx.JSON(http.StatusOK, response)}-// Upload-// @Summary Stream upload a basebackup or WAL segment-// @Description Accepts a zstd-compressed binary stream and stores it in the database's configured storage.-// The server generates the storage filename; agents do not control the destination path.-// WAL segments are accepted unconditionally+// UploadWalSegment+// @Summary Stream upload a WAL segment+// @Description Accepts a zstd-compressed WAL segment binary stream and stores it in the database's configured storage.+// WAL segments are accepted unconditionally.// @Tags backups-wal// @Accept application/octet-stream-// @Produce json// @Security AgentToken-// @Param X-Upload-Type header string true "Upload type" Enums(basebackup, wal)-// @Param X-Wal-Segment-Name header string false "24-hex WAL segment identifier (required for wal uploads, e.g. 0000000100000001000000AB)"-// @Param fullBackupWalStartSegment query string false "First WAL segment needed to make the basebackup consistent (required for basebackup uploads)"-// @Param fullBackupWalStopSegment query string false "Last WAL segment included in the basebackup (required for basebackup uploads)"+// @Param X-Wal-Segment-Name header string true "24-hex WAL segment identifier (e.g. 0000000100000001000000AB)"// @Success 204// @Failure 400 {object} map[string]string// @Failure 401 {object} map[string]string// @Failure 500 {object} map[string]string-// @Router /backups/postgres/wal/upload [post]-func (c *PostgreWalBackupController) Upload(ctx *gin.Context) {+// @Router /backups/postgres/wal/upload/wal [post]+func (c *PostgreWalBackupController) UploadWalSegment(ctx *gin.Context) {database, err := c.getDatabase(ctx)if err != nil {ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid agent token"})return}- uploadType := backups_core.PgWalUploadType(ctx.GetHeader("X-Upload-Type"))- if uploadType != backups_core.PgWalUploadTypeBasebackup &&- uploadType != backups_core.PgWalUploadTypeWal {+ walSegmentName := ctx.GetHeader("X-Wal-Segment-Name")+ if walSegmentName == "" {ctx.JSON(http.StatusBadRequest,- gin.H{"error": "X-Upload-Type must be 'basebackup' or 'wal'"},+ gin.H{"error": "X-Wal-Segment-Name is required for wal uploads"},)return}- walSegmentName := ""- if uploadType == backups_core.PgWalUploadTypeWal {- walSegmentName = ctx.GetHeader("X-Wal-Segment-Name")- if walSegmentName == "" {- ctx.JSON(- http.StatusBadRequest,- gin.H{"error": "X-Wal-Segment-Name is required for wal uploads"},- )- return- }+ uploadErr := c.walService.UploadWalSegment(+ ctx.Request.Context(),+ database,+ walSegmentName,+ ctx.Request.Body,+ )++ if uploadErr != nil {+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": uploadErr.Error()})+ return}- if uploadType == backups_core.PgWalUploadTypeBasebackup {- if ctx.Query("fullBackupWalStartSegment") == "" ||- ctx.Query("fullBackupWalStopSegment") == "" {- ctx.JSON(- http.StatusBadRequest,- gin.H{- "error": "fullBackupWalStartSegment and fullBackupWalStopSegment are required for basebackup uploads",- },- )- return- }+ ctx.Status(http.StatusNoContent)+}++// StartFullBackupUpload+// @Summary Stream upload a full basebackup (Phase 1)+// @Description Accepts a zstd-compressed basebackup binary stream and stores it in the database's configured storage.+// Returns a backupId that must be completed via /upload/full-complete with WAL segment names.+// @Tags backups-wal+// @Accept application/octet-stream+// @Produce json+// @Security AgentToken+// @Success 200 {object} backups_dto.UploadBasebackupResponse+// @Failure 401 {object} map[string]string+// @Failure 500 {object} map[string]string+// @Router /backups/postgres/wal/upload/full-start [post]+func (c *PostgreWalBackupController) StartFullBackupUpload(ctx *gin.Context) {+ database, err := c.getDatabase(ctx)+ if err != nil {+ ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid agent token"})+ return}- uploadErr := c.walService.UploadWal(+ backupID, uploadErr := c.walService.UploadBasebackup(ctx.Request.Context(),database,- uploadType,- walSegmentName,- ctx.Query("fullBackupWalStartSegment"),- ctx.Query("fullBackupWalStopSegment"),ctx.Request.Body,)@@ -192,7 +192,48 @@ func (c *PostgreWalBackupController) Upload(ctx *gin.Context) {return}- ctx.Status(http.StatusNoContent)+ ctx.JSON(http.StatusOK, backups_dto.UploadBasebackupResponse{+ BackupID: backupID,+ })+}++// CompleteFullBackupUpload+// @Summary Complete a previously uploaded basebackup (Phase 2)+// @Description Sets WAL segment names and marks the basebackup as completed, or marks it as failed if an error is provided.+// @Tags backups-wal+// @Accept json+// @Security AgentToken+// @Param request body backups_dto.FinalizeBasebackupRequest true "Completion details"+// @Success 200+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Failure 500 {object} map[string]string+// @Router /backups/postgres/wal/upload/full-complete [post]+func (c *PostgreWalBackupController) CompleteFullBackupUpload(ctx *gin.Context) {+ database, err := c.getDatabase(ctx)+ if err != nil {+ ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid agent token"})+ return+ }++ var request backups_dto.FinalizeBasebackupRequest+ if err := ctx.ShouldBindJSON(&request); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ if err := c.walService.FinalizeBasebackup(+ database,+ request.BackupID,+ request.StartSegment,+ request.StopSegment,+ request.Error,+ ); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ ctx.Status(http.StatusOK)}// GetRestorePlandiff --git a/backend/internal/features/backups/backups/controllers/postgres_wal_controller_test.go b/backend/internal/features/backups/backups/controllers/postgres_wal_controller_test.goindex 9d2edd38..2bafb901 100644--- a/backend/internal/features/backups/backups/controllers/postgres_wal_controller_test.go+++ b/backend/internal/features/backups/backups/controllers/postgres_wal_controller_test.go@@ -38,7 +38,7 @@ func Test_WalUpload_InProgressStatusSetBeforeStream(t *testing.T) {uploadBasebackup(t, router, agentToken, "000000010000000100000001", "000000010000000100000010")pr, pw := io.Pipe()- req := newWalUploadRequest(pr, agentToken, "wal", "000000010000000100000011", "", "")+ req := newWalSegmentUploadRequest(pr, agentToken, "000000010000000100000011")w := httptest.NewRecorder()done := make(chan struct{})@@ -67,7 +67,7 @@ func Test_WalUpload_CompletedStatusAfterSuccessfulStream(t *testing.T) {uploadBasebackup(t, router, agentToken, "000000010000000100000001", "000000010000000100000010")body := bytes.NewReader([]byte("wal segment content"))- req := newWalUploadRequest(body, agentToken, "wal", "000000010000000100000011", "", "")+ req := newWalSegmentUploadRequest(body, agentToken, "000000010000000100000011")w := httptest.NewRecorder()router.ServeHTTP(w, req)@@ -99,7 +99,7 @@ func Test_WalUpload_FailedStatusWithErrorOnStreamError(t *testing.T) {uploadBasebackup(t, router, agentToken, "000000010000000100000001", "000000010000000100000010")pr, pw := io.Pipe()- req := newWalUploadRequest(pr, agentToken, "wal", "000000010000000100000011", "", "")+ req := newWalSegmentUploadRequest(pr, agentToken, "000000010000000100000011")w := httptest.NewRecorder()done := make(chan struct{})@@ -129,25 +129,149 @@ func Test_WalUpload_FailedStatusWithErrorOnStreamError(t *testing.T) {assert.NotNil(t, walBackup.FailMessage)}-func Test_WalUpload_Basebackup_MissingWalSegments_Returns400(t *testing.T) {+func Test_WalUpload_Basebackup_StreamingUpload_Returns200WithBackupId(t *testing.T) {router, db, storage, agentToken, _ := createWalTestSetup(t)defer removeWalTestSetup(db, storage)body := bytes.NewReader([]byte("basebackup content"))- req := newWalUploadRequest(body, agentToken, backups_core.PgWalUploadTypeBasebackup, "", "", "")+ req, _ := http.NewRequest(http.MethodPost, "/api/v1/backups/postgres/wal/upload/full-start", body)+ req.Header.Set("Authorization", agentToken)+ req.Header.Set("Content-Type", "application/octet-stream")+ w := httptest.NewRecorder()++ router.ServeHTTP(w, req)++ require.Equal(t, http.StatusOK, w.Code)++ var response backups_dto.UploadBasebackupResponse+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &response))+ assert.NotEqual(t, uuid.Nil, response.BackupID)++ backup, err := backups_core.GetBackupRepository().FindByID(response.BackupID)+ require.NoError(t, err)+ assert.Equal(t, backups_core.BackupStatusInProgress, backup.Status)+ assert.NotNil(t, backup.UploadCompletedAt)+}++func Test_FinalizeBasebackup_ValidSegments_MarksCompleted(t *testing.T) {+ router, db, storage, agentToken, _ := createWalTestSetup(t)+ defer removeWalTestSetup(db, storage)++ backupID := uploadBasebackupPhase1(t, router, agentToken)++ completeFullBackupUpload(t, router, agentToken, backupID,+ "000000010000000100000001", "000000010000000100000010", nil)++ backup, err := backups_core.GetBackupRepository().FindByID(backupID)+ require.NoError(t, err)+ assert.Equal(t, backups_core.BackupStatusCompleted, backup.Status)+ require.NotNil(t, backup.PgFullBackupWalStartSegmentName)+ assert.Equal(t, "000000010000000100000001", *backup.PgFullBackupWalStartSegmentName)+ require.NotNil(t, backup.PgFullBackupWalStopSegmentName)+ assert.Equal(t, "000000010000000100000010", *backup.PgFullBackupWalStopSegmentName)+}++func Test_FinalizeBasebackup_WithError_MarksFailed(t *testing.T) {+ router, db, storage, agentToken, _ := createWalTestSetup(t)+ defer removeWalTestSetup(db, storage)++ backupID := uploadBasebackupPhase1(t, router, agentToken)++ errMsg := "pg_basebackup stderr parse failed"+ completeFullBackupUpload(t, router, agentToken, backupID, "", "", &errMsg)++ backup, err := backups_core.GetBackupRepository().FindByID(backupID)+ require.NoError(t, err)+ assert.Equal(t, backups_core.BackupStatusFailed, backup.Status)+ require.NotNil(t, backup.FailMessage)+ assert.Equal(t, errMsg, *backup.FailMessage)+}++func Test_FinalizeBasebackup_InvalidBackupId_Returns400(t *testing.T) {+ router, db, storage, agentToken, _ := createWalTestSetup(t)+ defer removeWalTestSetup(db, storage)++ nonExistentID := uuid.New()+ body, _ := json.Marshal(backups_dto.FinalizeBasebackupRequest{+ BackupID: nonExistentID,+ StartSegment: "000000010000000100000001",+ StopSegment: "000000010000000100000010",+ })++ req, _ := http.NewRequest(+ http.MethodPost,+ "/api/v1/backups/postgres/wal/upload/full-complete",+ bytes.NewReader(body),+ )+ req.Header.Set("Authorization", agentToken)+ req.Header.Set("Content-Type", "application/json")+w := httptest.NewRecorder()+ router.ServeHTTP(w, req)++ assert.Equal(t, http.StatusBadRequest, w.Code)+}++func Test_FinalizeBasebackup_AlreadyCompleted_Returns400(t *testing.T) {+ router, db, storage, agentToken, _ := createWalTestSetup(t)+ defer removeWalTestSetup(db, storage)++ backupID := uploadBasebackupPhase1(t, router, agentToken)++ completeFullBackupUpload(t, router, agentToken, backupID,+ "000000010000000100000001", "000000010000000100000010", nil)++ // Second finalize should fail.+ body, _ := json.Marshal(backups_dto.FinalizeBasebackupRequest{+ BackupID: backupID,+ StartSegment: "000000010000000100000001",+ StopSegment: "000000010000000100000010",+ })++ req, _ := http.NewRequest(+ http.MethodPost,+ "/api/v1/backups/postgres/wal/upload/full-complete",+ bytes.NewReader(body),+ )+ req.Header.Set("Authorization", agentToken)+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()router.ServeHTTP(w, req)assert.Equal(t, http.StatusBadRequest, w.Code)}+func Test_FinalizeBasebackup_InvalidToken_Returns401(t *testing.T) {+ router, db, storage, _, _ := createWalTestSetup(t)+ defer removeWalTestSetup(db, storage)++ body, _ := json.Marshal(backups_dto.FinalizeBasebackupRequest{+ BackupID: uuid.New(),+ StartSegment: "000000010000000100000001",+ StopSegment: "000000010000000100000010",+ })++ req, _ := http.NewRequest(+ http.MethodPost,+ "/api/v1/backups/postgres/wal/upload/full-complete",+ bytes.NewReader(body),+ )+ req.Header.Set("Authorization", "invalid-token")+ req.Header.Set("Content-Type", "application/json")++ w := httptest.NewRecorder()+ router.ServeHTTP(w, req)++ assert.Equal(t, http.StatusUnauthorized, w.Code)+}+func Test_WalUpload_WalSegment_WithoutFullBackup_Returns204(t *testing.T) {router, db, storage, agentToken, _ := createWalTestSetup(t)defer removeWalTestSetup(db, storage)body := bytes.NewReader([]byte("wal content"))- req := newWalUploadRequest(body, agentToken, "wal", "000000010000000100000001", "", "")+ req := newWalSegmentUploadRequest(body, agentToken, "000000010000000100000001")w := httptest.NewRecorder()router.ServeHTTP(w, req)@@ -164,7 +288,7 @@ func Test_WalUpload_WalSegment_WithGap_Returns204(t *testing.T) {// Skip ...0012, upload ...0013 — should succeed (no chain validation on upload).body := bytes.NewReader([]byte("wal content"))- req := newWalUploadRequest(body, agentToken, "wal", "000000010000000100000013", "", "")+ req := newWalSegmentUploadRequest(body, agentToken, "000000010000000100000013")w := httptest.NewRecorder()router.ServeHTTP(w, req)@@ -180,14 +304,14 @@ func Test_WalUpload_WalSegment_DuplicateSegment_Returns200Idempotent(t *testing.// Upload ...0011 once.body1 := bytes.NewReader([]byte("wal content"))- req1 := newWalUploadRequest(body1, agentToken, "wal", "000000010000000100000011", "", "")+ req1 := newWalSegmentUploadRequest(body1, agentToken, "000000010000000100000011")w1 := httptest.NewRecorder()router.ServeHTTP(w1, req1)require.Equal(t, http.StatusNoContent, w1.Code)// Upload the same segment again — must return 204 (idempotent).body2 := bytes.NewReader([]byte("wal content"))- req2 := newWalUploadRequest(body2, agentToken, "wal", "000000010000000100000011", "", "")+ req2 := newWalSegmentUploadRequest(body2, agentToken, "000000010000000100000011")w2 := httptest.NewRecorder()router.ServeHTTP(w2, req2)@@ -216,7 +340,7 @@ func Test_WalUpload_WalSegment_ValidNextSegment_Returns200AndCreatesRecord(t *te// First WAL segment after the full backup stop segment.body := bytes.NewReader([]byte("wal segment data"))- req := newWalUploadRequest(body, agentToken, "wal", "000000010000000100000011", "", "")+ req := newWalSegmentUploadRequest(body, agentToken, "000000010000000100000011")w := httptest.NewRecorder()router.ServeHTTP(w, req)@@ -547,29 +671,14 @@ func Test_GetNextFullBackupTime_WalSegmentAfterFullBackup_DoesNotImpactTime(t *tsetHourlyInterval(t, router, db.ID, ownerToken)- // Upload basebackup via API.- bbBody := bytes.NewReader([]byte("basebackup content"))- bbReq := newWalUploadRequest(- bbBody, agentToken, backups_core.PgWalUploadTypeBasebackup, "",- "000000010000000100000001", "000000010000000100000010",- )- bbW := httptest.NewRecorder()- router.ServeHTTP(bbW, bbReq)- require.Equal(t, http.StatusNoContent, bbW.Code)+ uploadBasebackup(t, router, agentToken,+ "000000010000000100000001", "000000010000000100000010")// Shift the full backup's CreatedAt to 2 hours ago.twoHoursAgo := time.Now().UTC().Add(-2 * time.Hour)updateLastFullBackupTime(t, db.ID, twoHoursAgo)- // Upload WAL segment via API.- walBody := bytes.NewReader([]byte("wal segment content"))- walReq := newWalUploadRequest(- walBody, agentToken, backups_core.PgWalUploadTypeWal,- "000000010000000100000011", "", "",- )- walW := httptest.NewRecorder()- router.ServeHTTP(walW, walReq)- require.Equal(t, http.StatusNoContent, walW.Code)+ uploadWalSegment(t, router, agentToken, "000000010000000100000011")var response backups_dto.GetNextFullBackupTimeResponsetest_utils.MakeGetRequestAndUnmarshal(@@ -598,15 +707,8 @@ func Test_GetNextFullBackupTime_FailedBasebackup_DoesNotImpactTime(t *testing.T)setHourlyInterval(t, router, db.ID, ownerToken)- // Upload a successful basebackup via API.- bbBody := bytes.NewReader([]byte("basebackup content"))- bbReq := newWalUploadRequest(- bbBody, agentToken, backups_core.PgWalUploadTypeBasebackup, "",- "000000010000000100000001", "000000010000000100000010",- )- bbW := httptest.NewRecorder()- router.ServeHTTP(bbW, bbReq)- require.Equal(t, http.StatusNoContent, bbW.Code)+ uploadBasebackup(t, router, agentToken,+ "000000010000000100000001", "000000010000000100000010")// Shift the full backup's CreatedAt to 2 hours ago.twoHoursAgo := time.Now().UTC().Add(-2 * time.Hour)@@ -653,15 +755,8 @@ func Test_GetNextFullBackupTime_NewCompletedFullBackup_ImpactsTime(t *testing.T)setHourlyInterval(t, router, db.ID, ownerToken)- // Upload first basebackup via API.- bb1 := bytes.NewReader([]byte("first basebackup"))- bb1Req := newWalUploadRequest(- bb1, agentToken, backups_core.PgWalUploadTypeBasebackup, "",- "000000010000000100000001", "000000010000000100000010",- )- bb1W := httptest.NewRecorder()- router.ServeHTTP(bb1W, bb1Req)- require.Equal(t, http.StatusNoContent, bb1W.Code)+ uploadBasebackup(t, router, agentToken,+ "000000010000000100000001", "000000010000000100000010")// Shift the first backup's CreatedAt to 3 hours ago.threeHoursAgo := time.Now().UTC().Add(-3 * time.Hour)@@ -685,15 +780,8 @@ func Test_GetNextFullBackupTime_NewCompletedFullBackup_ImpactsTime(t *testing.T)"first next time should be in the past (old backup)",)- // Upload second basebackup via API (created now).- bb2 := bytes.NewReader([]byte("second basebackup"))- bb2Req := newWalUploadRequest(- bb2, agentToken, backups_core.PgWalUploadTypeBasebackup, "",- "000000010000000100000011", "000000010000000100000020",- )- bb2W := httptest.NewRecorder()- router.ServeHTTP(bb2W, bb2Req)- require.Equal(t, http.StatusNoContent, bb2W.Code)+ uploadBasebackup(t, router, agentToken,+ "000000010000000100000011", "000000010000000100000020")var secondResponse backups_dto.GetNextFullBackupTimeResponsetest_utils.MakeGetRequestAndUnmarshal(@@ -931,15 +1019,18 @@ func Test_DownloadRestoreFile_UploadThenDownload_ContentMatches(t *testing.T) {uploadContent := "test-basebackup-content-for-download"body := bytes.NewReader([]byte(uploadContent))- req := newWalUploadRequest(- body, agentToken, backups_core.PgWalUploadTypeBasebackup, "",- "000000010000000100000001", "000000010000000100000010",- )+ req, _ := http.NewRequest(http.MethodPost, "/api/v1/backups/postgres/wal/upload/full-start", body)+ req.Header.Set("Authorization", agentToken)+ req.Header.Set("Content-Type", "application/octet-stream")w := httptest.NewRecorder()router.ServeHTTP(w, req)- require.Equal(t, http.StatusNoContent, w.Code)+ require.Equal(t, http.StatusOK, w.Code)++ var uploadResp backups_dto.UploadBasebackupResponse+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &uploadResp))- WaitForBackupCompletion(t, db.ID, 0, 5*time.Second)+ completeFullBackupUpload(t, router, agentToken, uploadResp.BackupID,+ "000000010000000100000001", "000000010000000100000010", nil)var planResp backups_dto.GetRestorePlanResponsetest_utils.MakeGetRequestAndUnmarshal(@@ -973,7 +1064,7 @@ func Test_DownloadRestoreFile_WalSegment_UploadThenDownload_ContentMatches(t *tewalContent := "test-wal-segment-content-for-download"body := bytes.NewReader([]byte(walContent))- req := newWalUploadRequest(body, agentToken, "wal", "000000010000000100000011", "", "")+ req := newWalSegmentUploadRequest(body, agentToken, "000000010000000100000011")w := httptest.NewRecorder()router.ServeHTTP(w, req)require.Equal(t, http.StatusNoContent, w.Code)@@ -1178,53 +1269,92 @@ func removeWalTestSetup(db *databases.Database, storage *storages.Storage) {storages.RemoveTestStorage(storage.ID)}-func newWalUploadRequest(+func newWalSegmentUploadRequest(body io.Reader,agentToken string,- uploadType backups_core.PgWalUploadType,- walSegmentName string,- walStart string,- walStop string,+ segmentName string,) *http.Request {- url := "/api/v1/backups/postgres/wal/upload"- if walStart != "" || walStop != "" {- url += "?fullBackupWalStartSegment=" + walStart + "&fullBackupWalStopSegment=" + walStop- }-- req, err := http.NewRequest(http.MethodPost, url, body)+ req, err := http.NewRequest(http.MethodPost, "/api/v1/backups/postgres/wal/upload/wal", body)if err != nil {panic(err)}req.Header.Set("Authorization", agentToken)req.Header.Set("Content-Type", "application/octet-stream")- req.Header.Set("X-Upload-Type", string(uploadType))-- if walSegmentName != "" {- req.Header.Set("X-Wal-Segment-Name", walSegmentName)- }+ req.Header.Set("X-Wal-Segment-Name", segmentName)return req}-func uploadBasebackup(+func uploadBasebackupPhase1(t *testing.T,router *gin.Engine,agentToken string,+) uuid.UUID {+ t.Helper()++ body := bytes.NewReader([]byte("test-basebackup-content"))++ req, _ := http.NewRequest(http.MethodPost, "/api/v1/backups/postgres/wal/upload/full-start", body)+ req.Header.Set("Authorization", agentToken)+ req.Header.Set("Content-Type", "application/octet-stream")++ w := httptest.NewRecorder()+ router.ServeHTTP(w, req)++ require.Equal(t, http.StatusOK, w.Code)++ var response backups_dto.UploadBasebackupResponse+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &response))+ require.NotEqual(t, uuid.Nil, response.BackupID)++ return response.BackupID+}++func completeFullBackupUpload(+ t *testing.T,+ router *gin.Engine,+ agentToken string,+ backupID uuid.UUID,walStart string,walStop string,+ errMsg *string,) {t.Helper()- body := bytes.NewReader([]byte("test-basebackup-content"))- req := newWalUploadRequest(- body, agentToken, backups_core.PgWalUploadTypeBasebackup, "",- walStart, walStop,+ request := backups_dto.FinalizeBasebackupRequest{+ BackupID: backupID,+ StartSegment: walStart,+ StopSegment: walStop,+ Error: errMsg,+ }++ reqBody, _ := json.Marshal(request)+ req, _ := http.NewRequest(+ http.MethodPost,+ "/api/v1/backups/postgres/wal/upload/full-complete",+ bytes.NewReader(reqBody),)+ req.Header.Set("Authorization", agentToken)+ req.Header.Set("Content-Type", "application/json")+w := httptest.NewRecorder()router.ServeHTTP(w, req)- require.Equal(t, http.StatusNoContent, w.Code)+ require.Equal(t, http.StatusOK, w.Code)+}++func uploadBasebackup(+ t *testing.T,+ router *gin.Engine,+ agentToken string,+ walStart string,+ walStop string,+) {+ t.Helper()++ backupID := uploadBasebackupPhase1(t, router, agentToken)+ completeFullBackupUpload(t, router, agentToken, backupID, walStart, walStop, nil)}func uploadWalSegment(@@ -1236,9 +1366,12 @@ func uploadWalSegment(t.Helper()body := bytes.NewReader([]byte("test-wal-segment-content"))- req := newWalUploadRequest(- body, agentToken, backups_core.PgWalUploadTypeWal, segmentName, "", "",- )++ req, _ := http.NewRequest(http.MethodPost, "/api/v1/backups/postgres/wal/upload/wal", body)+ req.Header.Set("Authorization", agentToken)+ req.Header.Set("Content-Type", "application/octet-stream")+ req.Header.Set("X-Wal-Segment-Name", segmentName)+w := httptest.NewRecorder()router.ServeHTTP(w, req)diff --git a/backend/internal/features/backups/backups/core/model.go b/backend/internal/features/backups/backups/core/model.goindex 9a4123aa..8ca49fd6 100644--- a/backend/internal/features/backups/backups/core/model.go+++ b/backend/internal/features/backups/backups/core/model.go@@ -43,7 +43,8 @@ type Backup struct {PgVersion *string `json:"pgVersion" gorm:"column:pg_version;type:text"`PgWalSegmentName *string `json:"pgWalSegmentName" gorm:"column:pg_wal_segment_name;type:text"`- CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"`+ UploadCompletedAt *time.Time `json:"uploadCompletedAt" gorm:"column:upload_completed_at"`+ CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"`}func (b *Backup) GenerateFilename(dbName string) {diff --git a/backend/internal/features/backups/backups/core/repository.go b/backend/internal/features/backups/backups/core/repository.goindex c422f80b..32256018 100644--- a/backend/internal/features/backups/backups/core/repository.go+++ b/backend/internal/features/backups/backups/core/repository.go@@ -349,6 +349,24 @@ func (r *BackupRepository) FindWalSegmentByName(return &backup, nil}+func (r *BackupRepository) FindStaleUploadedBasebackups(olderThan time.Time) ([]*Backup, error) {+ var backups []*Backup++ err := storage.+ GetDb().+ Where(+ "status = ? AND upload_completed_at IS NOT NULL AND upload_completed_at < ?",+ BackupStatusInProgress,+ olderThan,+ ).+ Find(&backups).Error+ if err != nil {+ return nil, err+ }++ return backups, nil+}+func (r *BackupRepository) FindLastWalSegmentAfter(databaseID uuid.UUID,afterSegmentName string,diff --git a/backend/internal/features/backups/backups/dto/dto.go b/backend/internal/features/backups/backups/dto/dto.goindex fe55b271..bd969c03 100644--- a/backend/internal/features/backups/backups/dto/dto.go+++ b/backend/internal/features/backups/backups/dto/dto.go@@ -77,3 +77,14 @@ type GetRestorePlanResponse struct {TotalSizeBytes int64 `json:"totalSizeBytes"`LatestAvailableSegment string `json:"latestAvailableSegment"`}++type UploadBasebackupResponse struct {+ BackupID uuid.UUID `json:"backupId"`+}++type FinalizeBasebackupRequest struct {+ BackupID uuid.UUID `json:"backupId" binding:"required"`+ StartSegment string `json:"startSegment" binding:"required"`+ StopSegment string `json:"stopSegment" binding:"required"`+ Error *string `json:"error"`+}diff --git a/backend/internal/features/backups/backups/services/postgres_wal_service.go b/backend/internal/features/backups/backups/services/postgres_wal_service.goindex a963fa91..c33b04d3 100644--- a/backend/internal/features/backups/backups/services/postgres_wal_service.go+++ b/backend/internal/features/backups/backups/services/postgres_wal_service.go@@ -30,29 +30,18 @@ type PostgreWalBackupService struct {backupService *BackupService}-// UploadWal accepts a streaming WAL segment or basebackup upload from the agent.-// WAL segments are accepted unconditionally-func (s *PostgreWalBackupService) UploadWal(+// UploadWalSegment accepts a streaming WAL segment upload from the agent.+// WAL segments are accepted unconditionally.+func (s *PostgreWalBackupService) UploadWalSegment(ctx context.Context,database *databases.Database,- uploadType backups_core.PgWalUploadType,walSegmentName string,- fullBackupWalStartSegment string,- fullBackupWalStopSegment string,body io.Reader,) error {if err := s.validateWalBackupType(database); err != nil {return err}- if uploadType == backups_core.PgWalUploadTypeBasebackup {- if fullBackupWalStartSegment == "" || fullBackupWalStopSegment == "" {- return fmt.Errorf(- "fullBackupWalStartSegment and fullBackupWalStopSegment are required for basebackup uploads",- )- }- }-backupConfig, err := s.backupConfigService.GetBackupConfigByDbId(database.ID)if err != nil {return fmt.Errorf("failed to get backup config: %w", err)@@ -62,26 +51,20 @@ func (s *PostgreWalBackupService) UploadWal(return fmt.Errorf("no storage configured for database %s", database.ID)}- if uploadType == backups_core.PgWalUploadTypeWal {- // Idempotency: skip if this segment was already uploaded.- existing, err := s.backupRepository.FindWalSegmentByName(database.ID, walSegmentName)- if err != nil {- return fmt.Errorf("failed to check for duplicate WAL segment: %w", err)- }+ existing, err := s.backupRepository.FindWalSegmentByName(database.ID, walSegmentName)+ if err != nil {+ return fmt.Errorf("failed to check for duplicate WAL segment: %w", err)+ }- if existing != nil {- return nil- }+ if existing != nil {+ return nil}- backup := s.createBackupRecord(+ backup := s.createWalSegmentRecord(database.ID,backupConfig.Storage.ID,- uploadType,database.Name,walSegmentName,- fullBackupWalStartSegment,- fullBackupWalStopSegment,backupConfig.Encryption,)@@ -102,6 +85,100 @@ func (s *PostgreWalBackupService) UploadWal(return nil}+// UploadBasebackup accepts a streaming basebackup upload from the agent (Phase 1).+// The backup stays IN_PROGRESS with UploadCompletedAt set after streaming finishes.+// The agent must call FinalizeBasebackup (Phase 2) with WAL segment names to complete.+func (s *PostgreWalBackupService) UploadBasebackup(+ ctx context.Context,+ database *databases.Database,+ body io.Reader,+) (uuid.UUID, error) {+ if err := s.validateWalBackupType(database); err != nil {+ return uuid.Nil, err+ }++ backupConfig, err := s.backupConfigService.GetBackupConfigByDbId(database.ID)+ if err != nil {+ return uuid.Nil, fmt.Errorf("failed to get backup config: %w", err)+ }++ if backupConfig.Storage == nil {+ return uuid.Nil, fmt.Errorf("no storage configured for database %s", database.ID)+ }++ backup := s.createBasebackupRecord(+ database.ID,+ backupConfig.Storage.ID,+ database.Name,+ backupConfig.Encryption,+ )++ if err := s.backupRepository.Save(backup); err != nil {+ return uuid.Nil, fmt.Errorf("failed to create backup record: %w", err)+ }++ sizeBytes, streamErr := s.streamToStorage(ctx, backup, backupConfig, body)+ if streamErr != nil {+ errMsg := streamErr.Error()+ s.markFailed(backup, errMsg)++ return uuid.Nil, fmt.Errorf("upload failed: %w", streamErr)+ }++ now := time.Now().UTC()+ backup.UploadCompletedAt = &now+ backup.BackupSizeMb = float64(sizeBytes) / (1024 * 1024)++ if err := s.backupRepository.Save(backup); err != nil {+ return uuid.Nil, fmt.Errorf("failed to update backup after upload: %w", err)+ }++ return backup.ID, nil+}++// FinalizeBasebackup completes a previously uploaded basebackup (Phase 2).+// Sets WAL segment names and marks the backup as COMPLETED, or marks it FAILED if errorMsg is provided.+func (s *PostgreWalBackupService) FinalizeBasebackup(+ database *databases.Database,+ backupID uuid.UUID,+ startSegment string,+ stopSegment string,+ errorMsg *string,+) error {+ if err := s.validateWalBackupType(database); err != nil {+ return err+ }++ backup, err := s.backupRepository.FindByID(backupID)+ if err != nil {+ return fmt.Errorf("backup not found: %w", err)+ }++ if backup.DatabaseID != database.ID {+ return fmt.Errorf("backup does not belong to this database")+ }++ if backup.Status != backups_core.BackupStatusInProgress || backup.UploadCompletedAt == nil {+ return fmt.Errorf("backup is not awaiting finalization")+ }++ if errorMsg != nil {+ s.markFailed(backup, *errorMsg)++ return nil+ }++ backup.PgFullBackupWalStartSegmentName = &startSegment+ backup.PgFullBackupWalStopSegmentName = &stopSegment+ backup.Status = backups_core.BackupStatusCompleted++ if err := s.backupRepository.Save(backup); err != nil {+ return fmt.Errorf("failed to finalize backup: %w", err)+ }++ return nil+}+func (s *PostgreWalBackupService) GetRestorePlan(database *databases.Database,backupID *uuid.UUID,@@ -331,46 +408,53 @@ func (s *PostgreWalBackupService) IsWalChainValid(}, nil}-func (s *PostgreWalBackupService) createBackupRecord(+func (s *PostgreWalBackupService) createBasebackupRecord(databaseID uuid.UUID,storageID uuid.UUID,- uploadType backups_core.PgWalUploadType,dbName string,- walSegmentName string,- fullBackupWalStartSegment string,- fullBackupWalStopSegment string,encryption backups_config.BackupEncryption,) *backups_core.Backup {now := time.Now().UTC()+ walBackupType := backups_core.PgWalBackupTypeFullBackupbackup := &backups_core.Backup{- ID: uuid.New(),- DatabaseID: databaseID,- StorageID: storageID,- Status: backups_core.BackupStatusInProgress,- Encryption: encryption,- CreatedAt: now,+ ID: uuid.New(),+ DatabaseID: databaseID,+ StorageID: storageID,+ Status: backups_core.BackupStatusInProgress,+ PgWalBackupType: &walBackupType,+ Encryption: encryption,+ CreatedAt: now,}backup.GenerateFilename(dbName)- if uploadType == backups_core.PgWalUploadTypeBasebackup {- walBackupType := backups_core.PgWalBackupTypeFullBackup- backup.PgWalBackupType = &walBackupType+ return backup+}- if fullBackupWalStartSegment != "" {- backup.PgFullBackupWalStartSegmentName = &fullBackupWalStartSegment- }+func (s *PostgreWalBackupService) createWalSegmentRecord(+ databaseID uuid.UUID,+ storageID uuid.UUID,+ dbName string,+ walSegmentName string,+ encryption backups_config.BackupEncryption,+) *backups_core.Backup {+ now := time.Now().UTC()+ walBackupType := backups_core.PgWalBackupTypeWalSegment- if fullBackupWalStopSegment != "" {- backup.PgFullBackupWalStopSegmentName = &fullBackupWalStopSegment- }- } else {- walBackupType := backups_core.PgWalBackupTypeWalSegment- backup.PgWalBackupType = &walBackupType- backup.PgWalSegmentName = &walSegmentName+ backup := &backups_core.Backup{+ ID: uuid.New(),+ DatabaseID: databaseID,+ StorageID: storageID,+ Status: backups_core.BackupStatusInProgress,+ PgWalBackupType: &walBackupType,+ PgWalSegmentName: &walSegmentName,+ Encryption: encryption,+ CreatedAt: now,}+ backup.GenerateFilename(dbName)+return backup}diff --git a/backend/migrations/20260316151706_add_upload_completed_at.sql b/backend/migrations/20260316151706_add_upload_completed_at.sqlnew file mode 100644index 00000000..d14b3321--- /dev/null+++ b/backend/migrations/20260316151706_add_upload_completed_at.sql@@ -0,0 +1,7 @@+-- +goose Up+ALTER TABLE backups+ ADD COLUMN upload_completed_at TIMESTAMPTZ;++-- +goose Down+ALTER TABLE backups+ DROP COLUMN upload_completed_at;