Skip to content

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

FEATURE (backups): Add download backup button

Rostislav Dugin2523a69f168f
diff --git a/backend/internal/features/backups/backups/controller.go b/backend/internal/features/backups/backups/controller.go
index 9dbe7631..f874e3e7 100644
--- a/backend/internal/features/backups/backups/controller.go
+++ b/backend/internal/features/backups/backups/controller.go
@@ -1,6 +1,8 @@
package backups
import (
+ "fmt"
+ "io"
"net/http"
"postgresus-backend/internal/features/users"
@@ -16,6 +18,7 @@ type BackupController struct {
func (c *BackupController) RegisterRoutes(router *gin.RouterGroup) {
router.GET("/backups", c.GetBackups)
router.POST("/backups", c.MakeBackup)
+ router.GET("/backups/:id/file", c.GetFile)
router.DELETE("/backups/:id", c.DeleteBackup)
}
@@ -140,6 +143,62 @@ func (c *BackupController) DeleteBackup(ctx *gin.Context) {
ctx.Status(http.StatusNoContent)
}
+// GetFile
+// @Summary Download a backup file
+// @Description Download the backup file for the specified backup
+// @Tags backups
+// @Param id path string true "Backup ID"
+// @Success 200 {file} file
+// @Failure 400
+// @Failure 401
+// @Failure 500
+// @Router /backups/{id}/file [get]
+func (c *BackupController) GetFile(ctx *gin.Context) {
+ id, err := uuid.Parse(ctx.Param("id"))
+ if err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid backup ID"})
+ return
+ }
+
+ authorizationHeader := ctx.GetHeader("Authorization")
+ if authorizationHeader == "" {
+ ctx.JSON(http.StatusUnauthorized, gin.H{"error": "authorization header is required"})
+ return
+ }
+
+ user, err := c.userService.GetUserFromToken(authorizationHeader)
+ if err != nil {
+ ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
+ return
+ }
+
+ fileReader, err := c.backupService.GetBackupFile(user, id)
+ if err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+ defer func() {
+ if err := fileReader.Close(); err != nil {
+ // Log the error but don't interrupt the response
+ fmt.Printf("Error closing file reader: %v\n", err)
+ }
+ }()
+
+ // Set headers for file download
+ ctx.Header("Content-Type", "application/octet-stream")
+ ctx.Header(
+ "Content-Disposition",
+ fmt.Sprintf("attachment; filename=\"backup_%s.dump\"", id.String()),
+ )
+
+ // Stream the file content
+ _, err = io.Copy(ctx.Writer, fileReader)
+ if err != nil {
+ ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to stream file"})
+ return
+ }
+}
+
type MakeBackupRequest struct {
DatabaseID uuid.UUID `json:"database_id" binding:"required"`
}
diff --git a/backend/internal/features/backups/backups/service.go b/backend/internal/features/backups/backups/service.go
index ac9deaba..f00ff221 100644
--- a/backend/internal/features/backups/backups/service.go
+++ b/backend/internal/features/backups/backups/service.go
@@ -3,6 +3,7 @@ package backups
import (
"errors"
"fmt"
+ "io"
"log/slog"
backups_config "postgresus-backend/internal/features/backups/config"
"postgresus-backend/internal/features/databases"
@@ -318,6 +319,22 @@ func (s *BackupService) GetBackup(backupID uuid.UUID) (*Backup, error) {
return s.backupRepository.FindByID(backupID)
}
+func (s *BackupService) GetBackupFile(
+ user *users_models.User,
+ backupID uuid.UUID,
+) (io.ReadCloser, error) {
+ backup, err := s.backupRepository.FindByID(backupID)
+ if err != nil {
+ return nil, err
+ }
+
+ if backup.Database.UserID != user.ID {
+ return nil, errors.New("user does not have access to this backup")
+ }
+
+ return backup.Storage.GetFile(backup.ID)
+}
+
func (s *BackupService) deleteBackup(backup *Backup) error {
for _, listener := range s.backupRemoveListeners {
if err := listener.OnBeforeBackupRemove(backup); err != nil {
diff --git a/contribute/README.md b/contribute/README.md
index bb12656a..752f45a7 100644
--- a/contribute/README.md
+++ b/contribute/README.md
@@ -47,11 +47,6 @@ If you need to add some explanation, do it in appropriate place in the code. Or
Before taking anything more than a couple of lines of code, please write Rostislav via Telegram (@rostislav_dugin) and confirm priority. It is possible that we already have something in the works, it is not needed or it's not project priority.
-Deploy flow:
-
-- add support of Kubernetes Helm (in progress by Rostislav Dugin)
-- add devcontainers for backend and frontend
-
Backups flow:
- add FTP
@@ -70,14 +65,14 @@ Notifications flow:
Extra:
+- add linters and formatters on each PR (in progress by Rostislav Dugin)
- add prettier labels to GitHub README
-- allow to download backup file (via streaming)
-- add linters and formatters on each PR
- add versioning instead of :latest
- create pretty website like rybbit.io with demo
- add HTTPS for Postgresus
- add simple SQL queries via UI
- add brute force protection on auth (via local RPS limiter)
+- add support of Kubernetes Helm
Monitoring flow:
diff --git a/frontend/src/entity/backups/api/backupsApi.ts b/frontend/src/entity/backups/api/backupsApi.ts
index 65d8c7ee..4ce32717 100644
--- a/frontend/src/entity/backups/api/backupsApi.ts
+++ b/frontend/src/entity/backups/api/backupsApi.ts
@@ -24,4 +24,8 @@ export const backupsApi = {
async deleteBackup(id: string) {
return apiHelper.fetchDeleteRaw(`${getApplicationServer()}/api/v1/backups/${id}`);
},
+
+ async downloadBackup(id: string): Promise<Blob> {
+ return apiHelper.fetchGetBlob(`${getApplicationServer()}/api/v1/backups/${id}/file`);
+ },
};
diff --git a/frontend/src/features/backups/ui/BackupsComponent.tsx b/frontend/src/features/backups/ui/BackupsComponent.tsx
index 8a5bc5ed..88385b1b 100644
--- a/frontend/src/features/backups/ui/BackupsComponent.tsx
+++ b/frontend/src/features/backups/ui/BackupsComponent.tsx
@@ -2,6 +2,7 @@ import {
CheckCircleOutlined,
CloudUploadOutlined,
DeleteOutlined,
+ DownloadOutlined,
ExclamationCircleOutlined,
InfoCircleOutlined,
SyncOutlined,
@@ -39,6 +40,36 @@ export const BackupsComponent = ({ database }: Props) => {
const isReloadInProgress = useRef(false);
+ const [downloadingBackupId, setDownloadingBackupId] = useState<string | undefined>();
+
+ const downloadBackup = async (backupId: string) => {
+ try {
+ const blob = await backupsApi.downloadBackup(backupId);
+
+ // Create a download link
+ const url = window.URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = url;
+
+ // Find the backup to get a meaningful filename
+ const backup = backups.find((b) => b.id === backupId);
+ const createdAt = backup ? dayjs(backup.createdAt).format('YYYY-MM-DD_HH-mm-ss') : 'backup';
+ link.download = `${database.name}_backup_${createdAt}.dump`;
+
+ // Trigger download
+ document.body.appendChild(link);
+ link.click();
+
+ // Cleanup
+ document.body.removeChild(link);
+ window.URL.revokeObjectURL(url);
+ } catch (e) {
+ alert((e as Error).message);
+ } finally {
+ setDownloadingBackupId(undefined);
+ }
+ };
+
const loadBackups = async () => {
if (isReloadInProgress.current) {
return;
@@ -114,6 +145,12 @@ export const BackupsComponent = ({ database }: Props) => {
return () => clearInterval(interval);
}, [database]);
+ useEffect(() => {
+ if (downloadingBackupId) {
+ downloadBackup(downloadingBackupId);
+ }
+ }, [downloadingBackupId]);
+
const columns: ColumnsType<Backup> = [
{
title: 'Created at',
@@ -272,6 +309,27 @@ export const BackupsComponent = ({ database }: Props) => {
}}
/>
</Tooltip>
+
+ <Tooltip
+ className="ml-3"
+ title="Download backup file. It can be restored manually via pg_restore (from custom format)"
+ >
+ {downloadingBackupId === record.id ? (
+ <SyncOutlined spin />
+ ) : (
+ <DownloadOutlined
+ className="cursor-pointer"
+ onClick={() => {
+ if (downloadingBackupId) return;
+ setDownloadingBackupId(record.id);
+ }}
+ style={{
+ opacity: downloadingBackupId ? 0.2 : 1,
+ color: '#0d6efd',
+ }}
+ />
+ )}
+ </Tooltip>
</>
)}
</div>
diff --git a/frontend/src/shared/api/apiHelper.ts b/frontend/src/shared/api/apiHelper.ts
index 0924e491..04813263 100644
--- a/frontend/src/shared/api/apiHelper.ts
+++ b/frontend/src/shared/api/apiHelper.ts
@@ -164,7 +164,6 @@ export const apiHelper = {
isRetryOnError = false,
): Promise<Blob> => {
const optionsWrapper = (requestOptions ?? new RequestOptions())
- .addHeader('Content-Type', 'application/json')
.addHeader('Access-Control-Allow-Methods', 'GET')
.addHeader('Authorization', accessTokenHelper.getAccessToken());