PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FEATURE (backups): Show when the next scheduled backup runs, computed from the rules the scheduler acts on (issue #807)
Rostislav Dugin4bb7ffa80fac
diff --git a/backend/internal/features/backups/backups/backuping/logical/scheduler.go b/backend/internal/features/backups/backups/backuping/logical/scheduler.goindex d6439061..96f0c423 100644--- a/backend/internal/features/backups/backups/backuping/logical/scheduler.go+++ b/backend/internal/features/backups/backups/backuping/logical/scheduler.go@@ -12,6 +12,7 @@ import (backups_core_logical "databasus-backend/internal/features/backups/backups/core/logical"backups_config_logical "databasus-backend/internal/features/backups/config/logical""databasus-backend/internal/features/databases"+ "databasus-backend/internal/features/intervals"task_cancellation "databasus-backend/internal/features/tasks/cancellation")@@ -251,6 +252,29 @@ func (s *BackupsScheduler) GetRemainedBackupTryCount(return remainedTryCount}+// GetNextScheduledBackup reads the same inputs runPendingBackups and StartBackup act on,+// so the reported time is when this scheduler will actually start the backup.+func (s *BackupsScheduler) GetNextScheduledBackup(+ databaseID uuid.UUID,+ now time.Time,+) (*intervals.NextTrigger, error) {+ backupConfig, err := s.backupConfigService.FindBackupConfigByDbId(databaseID)+ if err != nil {+ return nil, err+ }++ if backupConfig == nil || !backupConfig.IsBackupsEnabled || backupConfig.StorageID == nil {+ return nil, nil+ }++ lastBackup, err := s.backupRepository.FindLastByDatabaseID(databaseID)+ if err != nil {+ return nil, err+ }++ return backupConfig.BackupInterval.GetNextTrigger(now, createdAtOrNil(lastBackup)), nil+}+func (s *BackupsScheduler) runPendingBackups(ctx context.Context, logger *slog.Logger) error {enabledBackupConfigs, err := s.backupConfigService.GetBackupConfigsWithEnabledBackups()if err != nil {@@ -270,10 +294,7 @@ func (s *BackupsScheduler) runPendingBackups(ctx context.Context, logger *slog.Lcontinue}- var lastBackupTime *time.Time- if lastBackup != nil {- lastBackupTime = &lastBackup.CreatedAt- }+ lastBackupTime := createdAtOrNil(lastBackup)remainedBackupTryCount := s.GetRemainedBackupTryCount(ctx, logger, lastBackup)@@ -359,3 +380,11 @@ func (s *BackupsScheduler) onBackupCompleted(backupID uuid.UUID) {go listener.OnBackupCompleted(backupID)}}++func createdAtOrNil(backup *backups_core_logical.LogicalBackup) *time.Time {+ if backup == nil {+ return nil+ }++ return &backup.CreatedAt+}diff --git a/backend/internal/features/backups/backups/backuping/physical/scheduler.go b/backend/internal/features/backups/backups/backuping/physical/scheduler.goindex b3eec17f..9f6dcede 100644--- a/backend/internal/features/backups/backups/backuping/physical/scheduler.go+++ b/backend/internal/features/backups/backups/backuping/physical/scheduler.go@@ -18,6 +18,7 @@ import (physical_repositories "databasus-backend/internal/features/backups/backups/core/physical/repositories"backups_config_physical "databasus-backend/internal/features/backups/config/physical"postgresql_physical "databasus-backend/internal/features/databases/databases/postgresql/physical"+ "databasus-backend/internal/features/intervals"storage_files "databasus-backend/internal/features/storages/files"tasks_cancellation "databasus-backend/internal/features/tasks/cancellation""databasus-backend/internal/storage"@@ -112,6 +113,61 @@ func (s *PhysicalBackupsScheduler) Run(ctx context.Context) {}}+// GetNextScheduledBackups reads the same inputs evaluateConfig and decideBackupKind act on,+// so the reported times are when this scheduler will actually start each cadence.+func (s *PhysicalBackupsScheduler) GetNextScheduledBackups(+ databaseID uuid.UUID,+ now time.Time,+) (nextFullBackup, nextIncrementalBackup *intervals.NextTrigger, err error) {+ backupConfig, err := s.backupConfigService.FindBackupConfigByDbId(databaseID)+ if err != nil {+ return nil, nil, err+ }++ if backupConfig == nil || !backupConfig.IsBackupsEnabled || backupConfig.StorageID == nil {+ return nil, nil, nil+ }++ hasUnresolvedMismatch, err := hasUnresolvedSystemIdentifierMismatch(storage.GetDb(), databaseID)+ if err != nil {+ return nil, nil, err+ }++ if hasUnresolvedMismatch {+ return nil, nil, nil+ }++ lastFull, err := s.fullRepo.FindLastFullAnyStatusByDatabase(databaseID)+ if err != nil {+ return nil, nil, err+ }++ nextFullBackup = backupConfig.FullBackupInterval.GetNextTrigger(now, createdAtOrNil(lastFull))++ if !isIncrementalEnabled(backupConfig) {+ return nextFullBackup, nil, nil+ }++ lastIncr, err := s.incrRepo.FindLastByDatabase(databaseID)+ if err != nil {+ return nil, nil, err+ }++ isHeldBack, err := s.isIncrementalChainHeldBack(databaseID, lastIncr)+ if err != nil {+ return nil, nil, err+ }++ if isHeldBack {+ return nextFullBackup, nil, nil+ }++ nextIncrementalBackup = backupConfig.IncrementalBackupInterval.GetNextTrigger(+ now, newestCreatedAt(lastFull, lastIncr))++ return nextFullBackup, nextIncrementalBackup, nil+}+func (s *PhysicalBackupsScheduler) runPendingBackups(ctx context.Context, logger *slog.Logger) error {enabledConfigs, err := s.backupConfigService.GetBackupConfigsWithEnabledBackups()if err != nil {@@ -266,6 +322,27 @@ func (s *PhysicalBackupsScheduler) decideBackupKind(}, true}+func (s *PhysicalBackupsScheduler) isIncrementalChainHeldBack(+ databaseID uuid.UUID,+ lastIncr *physical_models.PhysicalIncrementalBackup,+) (bool, error) {+ extendableChain, err := s.chainViewService.FindLastExtendableChainByDatabase(databaseID)+ if err != nil {+ return false, err+ }++ if extendableChain != nil {+ return false, nil+ }++ holdBackReason, err := s.getChainlessIncrementalHoldBackReason(databaseID, lastIncr)+ if err != nil {+ return false, err+ }++ return holdBackReason != "", nil+}+// decideForcedIncremental honors an out-of-cadence incremental request. It can// only be satisfied when incrementals are enabled and an extendable chain// exists; otherwise the stale request is cleared (so it can't loop forever) and@@ -876,24 +953,15 @@ func (s *PhysicalBackupsScheduler) decideReAnchoringFull(backupConfig *backups_config_physical.PhysicalBackupConfig,lastIncr *physical_models.PhysicalIncrementalBackup,) (backupDecision, bool) {- if isChainBrokenBySummarizerOff(lastIncr) {- logger.Debug("nothing due: chain broken by summarizer off, which a fresh FULL cannot fix")-- return backupDecision{}, false- }-- recentFullBackups, err := s.fullRepo.FindNewestAnyStatusByDatabase(- backupConfig.DatabaseID, recentFullAttemptsWindow)+ holdBackReason, err := s.getChainlessIncrementalHoldBackReason(backupConfig.DatabaseID, lastIncr)if err != nil {logger.Error("failed to find recent full backups", "error", err)return backupDecision{}, false}- if hasNoRecentCompletedFull(recentFullBackups) {- logger.Debug(fmt.Sprintf(- "nothing due: no extendable chain and no completed full among the newest %d",- recentFullAttemptsWindow))+ if holdBackReason != "" {+ logger.Debug(holdBackReason)return backupDecision{}, false}@@ -904,6 +972,31 @@ func (s *PhysicalBackupsScheduler) decideReAnchoringFull(}, true}+// getChainlessIncrementalHoldBackReason answers, for a database with no extendable+// chain, why a due incremental cadence must not re-anchor with a FULL. An empty+// reason means re-anchoring may go ahead.+func (s *PhysicalBackupsScheduler) getChainlessIncrementalHoldBackReason(+ databaseID uuid.UUID,+ lastIncr *physical_models.PhysicalIncrementalBackup,+) (string, error) {+ if isChainBrokenBySummarizerOff(lastIncr) {+ return "nothing due: chain broken by summarizer off, which a fresh FULL cannot fix", nil+ }++ recentFullBackups, err := s.fullRepo.FindNewestAnyStatusByDatabase(databaseID, recentFullAttemptsWindow)+ if err != nil {+ return "", err+ }++ if hasNoRecentCompletedFull(recentFullBackups) {+ return fmt.Sprintf(+ "nothing due: no extendable chain and no completed full among the newest %d",+ recentFullAttemptsWindow), nil+ }++ return "", nil+}+// The newest incremental row is the right witness: any completed INCR after it// would have kept the chain extendable, so this branch would not run at all.// Once the operator re-enables summarize_wal, incrementals resume with the nextdiff --git a/backend/internal/features/backups/backups/controllers/logical/controller.go b/backend/internal/features/backups/backups/controllers/logical/controller.goindex 95edffdc..94dd5d16 100644--- a/backend/internal/features/backups/backups/controllers/logical/controller.go+++ b/backend/internal/features/backups/backups/controllers/logical/controller.go@@ -26,6 +26,7 @@ type BackupController struct {func (c *BackupController) RegisterRoutes(router *gin.RouterGroup) {router.GET("/backups", c.GetBackups)+ router.GET("/backups/database/:id/next-backup", c.GetNextScheduledBackup)router.POST("/backups", c.MakeBackup)router.POST("/backups/:id/download-token", c.GenerateDownloadToken)router.DELETE("/backups/:id", c.DeleteBackup)@@ -91,6 +92,39 @@ func (c *BackupController) GetBackups(ctx *gin.Context) {ctx.JSON(http.StatusOK, response)}+// GetNextScheduledBackup+// @Summary Get the next scheduled backup of a logical database+// @Description Get when the scheduler will start the next automatic backup. nextBackup is null when no automatic backup will run.+// @Tags backups+// @Produce json+// @Security BearerAuth+// @Param id path string true "Database ID"+// @Success 200 {object} backups_dto_logical.GetNextScheduledBackupResponse+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Router /backups/database/{id}/next-backup [get]+func (c *BackupController) GetNextScheduledBackup(ctx *gin.Context) {+ user, ok := users_middleware.GetUserFromContext(ctx)+ if !ok {+ ctx.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})+ return+ }++ databaseID, err := uuid.Parse(ctx.Param("id"))+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid database ID"})+ return+ }++ response, err := c.backupService.GetNextScheduledBackup(ctx.Request.Context(), user, databaseID)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, response)+}+// MakeBackup// @Summary Create a backup// @Description Create a new backup for the specified databasediff --git a/backend/internal/features/backups/backups/controllers/logical/controller_test.go b/backend/internal/features/backups/backups/controllers/logical/controller_test.goindex a84cc856..0fb09c0d 100644--- a/backend/internal/features/backups/backups/controllers/logical/controller_test.go+++ b/backend/internal/features/backups/backups/controllers/logical/controller_test.go@@ -30,6 +30,8 @@ import (backups_config_logical "databasus-backend/internal/features/backups/config/logical""databasus-backend/internal/features/databases"postgresql_logical "databasus-backend/internal/features/databases/databases/postgresql/logical"+ "databasus-backend/internal/features/intervals"+ "databasus-backend/internal/features/notifiers""databasus-backend/internal/features/storages"storage_files "databasus-backend/internal/features/storages/files"local_storage "databasus-backend/internal/features/storages/models/local"@@ -1701,3 +1703,270 @@ func Test_DeleteBackup_RemovesBackupAndMetadataFilesFromDisk(t *testing.T) {_, err = os.Stat(metadataFilePath)assert.True(t, os.IsNotExist(err), "metadata file should be removed from disk after deletion")}++func Test_GetNextScheduledBackup_WhenDailySlotIsAhead_ReturnsSlot(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)+ database := createTestDatabase("Test Database", workspace.ID, owner.Token, router)+ storage := createTestStorage(workspace.ID)+ defer cleanupNextScheduledBackupTest(t, database, storage, workspace, router)++ now := time.Now().UTC()+ dailySlot := now.Add(3 * time.Hour).Truncate(time.Minute)+ saveNextScheduledBackupTestConfig(t, database.ID, &storage.ID, true, intervals.Interval{+ Type: intervals.IntervalDaily,+ TimeOfDay: new(dailySlot.Format("15:04")),+ })+ CreateTestBackupWithOptions(database.ID, storage.ID, TestBackupOptions{+ Status: backups_core_logical.BackupStatusCompleted,+ CreatedAt: now,+ })++ response := getNextScheduledBackup(t, router, database.ID, owner.Token)++ require.NotNil(t, response.NextBackup)+ assert.False(t, response.NextBackup.IsDue)+ assert.True(t, dailySlot.Equal(response.NextBackup.ScheduledAt),+ "next backup %s, reported %s", dailySlot, response.NextBackup.ScheduledAt)+}++func Test_GetNextScheduledBackup_WhenDailySlotWasMissed_ReportsDue(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)+ database := createTestDatabase("Test Database", workspace.ID, owner.Token, router)+ storage := createTestStorage(workspace.ID)+ defer cleanupNextScheduledBackupTest(t, database, storage, workspace, router)++ saveNextScheduledBackupTestConfig(t, database.ID, &storage.ID, true, intervals.Interval{+ Type: intervals.IntervalDaily,+ TimeOfDay: new("03:00"),+ })+ CreateTestBackupWithOptions(database.ID, storage.ID, TestBackupOptions{+ Status: backups_core_logical.BackupStatusFailed,+ CreatedAt: time.Now().UTC().AddDate(0, 0, -3),+ })++ response := getNextScheduledBackup(t, router, database.ID, owner.Token)++ require.NotNil(t, response.NextBackup)+ assert.True(t, response.NextBackup.IsDue)+}++func Test_GetNextScheduledBackup_WhenHourlyBackupFailed_CountsFailedBackup(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)+ database := createTestDatabase("Test Database", workspace.ID, owner.Token, router)+ storage := createTestStorage(workspace.ID)+ defer cleanupNextScheduledBackupTest(t, database, storage, workspace, router)++ failedBackupTime := time.Now().UTC().Add(-20 * time.Minute).Truncate(time.Second)+ saveNextScheduledBackupTestConfig(t, database.ID, &storage.ID, true, intervals.Interval{+ Type: intervals.IntervalHourly,+ })+ CreateTestBackupWithOptions(database.ID, storage.ID, TestBackupOptions{+ Status: backups_core_logical.BackupStatusCompleted,+ CreatedAt: failedBackupTime.Add(-5 * time.Hour),+ })+ CreateTestBackupWithOptions(database.ID, storage.ID, TestBackupOptions{+ Status: backups_core_logical.BackupStatusFailed,+ CreatedAt: failedBackupTime,+ })++ response := getNextScheduledBackup(t, router, database.ID, owner.Token)++ require.NotNil(t, response.NextBackup)+ assert.False(t, response.NextBackup.IsDue)+ assert.True(t, failedBackupTime.Add(time.Hour).Equal(response.NextBackup.ScheduledAt),+ "next backup %s, reported %s", failedBackupTime.Add(time.Hour), response.NextBackup.ScheduledAt)+}++func Test_GetNextScheduledBackup_WhenNoBackupExists_ReportsDue(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)+ database := createTestDatabase("Test Database", workspace.ID, owner.Token, router)+ storage := createTestStorage(workspace.ID)+ defer cleanupNextScheduledBackupTest(t, database, storage, workspace, router)++ saveNextScheduledBackupTestConfig(t, database.ID, &storage.ID, true, intervals.Interval{+ Type: intervals.IntervalDaily,+ TimeOfDay: new("03:00"),+ })++ response := getNextScheduledBackup(t, router, database.ID, owner.Token)++ require.NotNil(t, response.NextBackup)+ assert.True(t, response.NextBackup.IsDue)+}++func Test_GetNextScheduledBackup_WhenAutomaticBackupsWillNotRun_ReturnsNoNextBackup(t *testing.T) {+ testCases := []struct {+ name string+ isBackupsEnabled bool+ hasStorage bool+ }{+ {name: "backups disabled", isBackupsEnabled: false, hasStorage: true},+ {name: "storage missing", isBackupsEnabled: true, hasStorage: false},+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)+ database := createTestDatabase("Test Database", workspace.ID, owner.Token, router)+ storage := createTestStorage(workspace.ID)+ defer cleanupNextScheduledBackupTest(t, database, storage, workspace, router)++ var storageID *uuid.UUID+ if testCase.hasStorage {+ storageID = &storage.ID+ }++ saveNextScheduledBackupTestConfig(t, database.ID, storageID, testCase.isBackupsEnabled,+ intervals.Interval{Type: intervals.IntervalDaily, TimeOfDay: new("03:00")})++ response := getNextScheduledBackup(t, router, database.ID, owner.Token)++ assert.Nil(t, response.NextBackup)+ })+ }+}++func Test_GetNextScheduledBackup_WhenBackupConfigWasNeverSaved_ReturnsNoNextBackupAndCreatesNoConfig(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)+ database := createTestDatabase("Test Database", workspace.ID, owner.Token, router)+ storage := createTestStorage(workspace.ID)+ defer cleanupNextScheduledBackupTest(t, database, storage, workspace, router)++ response := getNextScheduledBackup(t, router, database.ID, owner.Token)++ assert.Nil(t, response.NextBackup)++ backupConfig, err := backups_config_logical.GetBackupConfigService().FindBackupConfigByDbId(database.ID)+ require.NoError(t, err)+ assert.Nil(t, backupConfig)+}++func Test_GetNextScheduledBackup_WhenDatabaseIsPhysical_ReturnsBadRequest(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)+ notifier := notifiers.CreateTestNotifier(workspace.ID)+ database := databases.CreateTestPhysicalPostgresDatabase(workspace.ID, notifier, "17")+ defer func() {+ databases.RemoveTestDatabase(t.Context(), database)+ notifiers.RemoveTestNotifier(notifier)+ workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)+ }()++ response := test_utils.MakeGetRequest(+ t,+ router,+ "/api/v1/backups/database/"+database.ID.String()+"/next-backup",+ "Bearer "+owner.Token,+ http.StatusBadRequest,+ )++ assert.Contains(t, string(response.Body), "physical backups")+}++func Test_GetNextScheduledBackup_WhenUserIsOutsideWorkspace_ReturnsBadRequest(t *testing.T) {+ router := createTestRouter()+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)+ database := createTestDatabase("Test Database", workspace.ID, owner.Token, router)+ storage := createTestStorage(workspace.ID)+ defer cleanupNextScheduledBackupTest(t, database, storage, workspace, router)++ saveNextScheduledBackupTestConfig(t, database.ID, &storage.ID, true, intervals.Interval{+ Type: intervals.IntervalDaily,+ TimeOfDay: new("03:00"),+ })+ nonMember := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)++ response := test_utils.MakeGetRequest(+ t,+ router,+ "/api/v1/backups/database/"+database.ID.String()+"/next-backup",+ "Bearer "+nonMember.Token,+ http.StatusBadRequest,+ )++ assert.Contains(t, string(response.Body), "insufficient permissions")+ assert.NotContains(t, string(response.Body), "nextBackup")+}++func Test_GetNextScheduledBackup_WhenRequestIsUnauthenticated_ReturnsUnauthorized(t *testing.T) {+ router := createTestRouter()++ test_utils.MakeGetRequest(+ t,+ router,+ "/api/v1/backups/database/"+uuid.New().String()+"/next-backup",+ "",+ http.StatusUnauthorized,+ )+}++func getNextScheduledBackup(+ t *testing.T,+ router *gin.Engine,+ databaseID uuid.UUID,+ token string,+) *backups_dto_logical.GetNextScheduledBackupResponse {+ t.Helper()++ var response backups_dto_logical.GetNextScheduledBackupResponse+ test_utils.MakeGetRequestAndUnmarshal(+ t,+ router,+ "/api/v1/backups/database/"+databaseID.String()+"/next-backup",+ "Bearer "+token,+ http.StatusOK,+ &response,+ )++ return &response+}++func saveNextScheduledBackupTestConfig(+ t *testing.T,+ databaseID uuid.UUID,+ storageID *uuid.UUID,+ isBackupsEnabled bool,+ interval intervals.Interval,+) {+ t.Helper()++ configService := backups_config_logical.GetBackupConfigService()++ backupConfig, err := configService.GetBackupConfigByDbId(databaseID)+ require.NoError(t, err)++ backupConfig.IsBackupsEnabled = isBackupsEnabled+ backupConfig.StorageID = storageID+ backupConfig.Storage = nil+ backupConfig.BackupInterval = interval++ _, err = configService.SaveBackupConfig(t.Context(), backupConfig)+ require.NoError(t, err)+}++func cleanupNextScheduledBackupTest(+ t *testing.T,+ database *databases.Database,+ storage *storages.Storage,+ workspace *workspaces_models.Workspace,+ router *gin.Engine,+) {+ databases.RemoveTestDatabase(t.Context(), database)+ time.Sleep(50 * time.Millisecond)+ storages.RemoveTestStorage(t.Context(), storage.ID)+ workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)+}diff --git a/backend/internal/features/backups/backups/controllers/physical/controller.go b/backend/internal/features/backups/backups/controllers/physical/controller.goindex 613837cf..1d360f48 100644--- a/backend/internal/features/backups/backups/controllers/physical/controller.go+++ b/backend/internal/features/backups/backups/controllers/physical/controller.go@@ -27,6 +27,7 @@ type PhysicalBackupController struct {func (c *PhysicalBackupController) RegisterRoutes(router *gin.RouterGroup) {router.GET("/backups/physical/database/:id/backups", c.GetBackups)+ router.GET("/backups/physical/database/:id/next-backups", c.GetNextScheduledBackups)router.POST("/backups/physical/database/:id/trigger", c.TriggerBackup)router.POST("/backups/physical/database/:id/restore-token", c.GenerateRestoreToken)@@ -97,6 +98,39 @@ func (c *PhysicalBackupController) GetBackups(ctx *gin.Context) {ctx.JSON(http.StatusOK, response)}+// GetNextScheduledBackups+// @Summary Get the next scheduled backups of a physical database+// @Description Get when the scheduler will start the next automatic full and incremental backups. A field is null when no such automatic backup will run.+// @Tags backups-physical+// @Produce json+// @Security BearerAuth+// @Param id path string true "Database ID"+// @Success 200 {object} backups_dto_physical.GetNextScheduledBackupsResponse+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Router /backups/physical/database/{id}/next-backups [get]+func (c *PhysicalBackupController) GetNextScheduledBackups(ctx *gin.Context) {+ user, ok := users_middleware.GetUserFromContext(ctx)+ if !ok {+ ctx.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})+ return+ }++ databaseID, err := uuid.Parse(ctx.Param("id"))+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid database ID"})+ return+ }++ response, err := c.physicalBackupService.GetNextScheduledBackups(ctx.Request.Context(), user, databaseID)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, response)+}+// TriggerBackup// @Summary Trigger a physical backup// @Description Requests an out-of-cadence backup, honored on the scheduler's next tick. type=full forces a new full; type=incremental extends the current chain (409 if none); type=auto lets the scheduler pick.diff --git a/backend/internal/features/backups/backups/controllers/physical/controller_test.go b/backend/internal/features/backups/backups/controllers/physical/controller_test.goindex 0a297143..dd11eb96 100644--- a/backend/internal/features/backups/backups/controllers/physical/controller_test.go+++ b/backend/internal/features/backups/backups/controllers/physical/controller_test.go@@ -7,6 +7,7 @@ import ("encoding/json""io""net/http"+ "strconv""strings""testing""time"@@ -17,6 +18,7 @@ import ("github.com/stretchr/testify/assert""github.com/stretchr/testify/require"+ "databasus-backend/internal/config"audit_logs "databasus-backend/internal/features/audit_logs"backuping_physical "databasus-backend/internal/features/backups/backups/backuping/physical"backups_controllers_physical "databasus-backend/internal/features/backups/backups/controllers/physical"@@ -29,6 +31,8 @@ import (backups_dto_physical "databasus-backend/internal/features/backups/backups/dto/physical"backups_config_physical "databasus-backend/internal/features/backups/config/physical""databasus-backend/internal/features/databases"+ postgresql_physical "databasus-backend/internal/features/databases/databases/postgresql/physical"+ "databasus-backend/internal/features/intervals""databasus-backend/internal/features/notifiers""databasus-backend/internal/features/storages"users_dto "databasus-backend/internal/features/users/dto"@@ -1590,3 +1594,275 @@ func readTarEntryNames(t *testing.T, body []byte) []string {return names}++func Test_GetNextScheduledBackups_WhenFullAndIncrementalEnabled_ReturnsBoth(t *testing.T) {+ testCases := []struct {+ name string+ backupType postgresql_physical.BackupType+ }{+ {name: "full and incremental", backupType: postgresql_physical.BackupTypeFullAndIncremental},+ {+ name: "full, incremental and WAL stream",+ backupType: postgresql_physical.BackupTypeFullIncrementalAndWalStream,+ },+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ prereqs := createNextScheduledBackupsPrereqs(t, testCase.backupType)+ saveNextScheduledBackupsTestConfig(t, prereqs, &prereqs.storage.ID)++ lastFullTime := time.Now().UTC().Add(-2 * time.Hour).Truncate(time.Second)+ lastIncrementalTime := time.Now().UTC().Add(-20 * time.Minute).Truncate(time.Second)+ full := createNextScheduledBackupsTestFull(+ t, prereqs, physical_enums.PhysicalBackupStatusCompleted, lastFullTime)+ createNextScheduledBackupsTestIncremental(+ t, prereqs, full.ID, physical_enums.PhysicalBackupStatusCompleted, lastIncrementalTime)++ response := getNextScheduledBackups(t, prereqs, prereqs.user.Token)++ require.NotNil(t, response.NextFullBackup)+ assert.False(t, response.NextFullBackup.IsDue)+ require.NotNil(t, response.NextIncrementalBackup)+ assert.False(t, response.NextIncrementalBackup.IsDue)+ assert.True(t, lastIncrementalTime.Add(time.Hour).Equal(response.NextIncrementalBackup.ScheduledAt),+ "next incremental backup %s, reported %s",+ lastIncrementalTime.Add(time.Hour), response.NextIncrementalBackup.ScheduledAt)+ })+ }+}++func Test_GetNextScheduledBackups_WhenFullOnly_ReturnsNoIncremental(t *testing.T) {+ prereqs := createNextScheduledBackupsPrereqs(t, postgresql_physical.BackupTypeFullOnly)+ saveNextScheduledBackupsTestConfig(t, prereqs, &prereqs.storage.ID)++ response := getNextScheduledBackups(t, prereqs, prereqs.user.Token)++ require.NotNil(t, response.NextFullBackup)+ assert.True(t, response.NextFullBackup.IsDue)+ assert.Nil(t, response.NextIncrementalBackup)+}++func Test_GetNextScheduledBackups_WhenAutomaticBackupsWillNotRun_ReturnsNeither(t *testing.T) {+ t.Run("backups disabled", func(t *testing.T) {+ prereqs := createNextScheduledBackupsPrereqs(t, postgresql_physical.BackupTypeFullAndIncremental)+ backupConfig := saveNextScheduledBackupsTestConfig(t, prereqs, &prereqs.storage.ID)++ backupConfig.IsBackupsEnabled = false+ _, err := backups_config_physical.GetBackupConfigService().SaveBackupConfig(t.Context(), backupConfig)+ require.NoError(t, err)++ assertNoNextScheduledBackups(t, getNextScheduledBackups(t, prereqs, prereqs.user.Token))+ })++ t.Run("storage missing", func(t *testing.T) {+ prereqs := createNextScheduledBackupsPrereqs(t, postgresql_physical.BackupTypeFullAndIncremental)+ saveNextScheduledBackupsTestConfig(t, prereqs, nil)++ assertNoNextScheduledBackups(t, getNextScheduledBackups(t, prereqs, prereqs.user.Token))+ })++ t.Run("backup config never saved", func(t *testing.T) {+ prereqs := createNextScheduledBackupsPrereqs(t, postgresql_physical.BackupTypeFullAndIncremental)++ assertNoNextScheduledBackups(t, getNextScheduledBackups(t, prereqs, prereqs.user.Token))++ backupConfig, err := backups_config_physical.GetBackupConfigService().FindBackupConfigByDbId(+ prereqs.database.ID)+ require.NoError(t, err)+ assert.Nil(t, backupConfig)+ })++ t.Run("system identifier mismatch unresolved", func(t *testing.T) {+ prereqs := createNextScheduledBackupsPrereqs(t, postgresql_physical.BackupTypeFullAndIncremental)+ saveNextScheduledBackupsTestConfig(t, prereqs, &prereqs.storage.ID)++ mismatchedFull := createNextScheduledBackupsTestFull(+ t, prereqs, physical_enums.PhysicalBackupStatusError, time.Now().UTC().Add(-time.Hour))+ mismatchedFull.ErrorReason = new(physical_enums.PhysicalBackupErrorSystemIdentifierMismatch)+ require.NoError(t, physical_repositories.GetFullBackupRepository().Save(mismatchedFull))++ assertNoNextScheduledBackups(t, getNextScheduledBackups(t, prereqs, prereqs.user.Token))+ })+}++func Test_GetNextScheduledBackups_WhenIncrementalChainIsHeldBack_ReturnsFullOnly(t *testing.T) {+ t.Run("chain broken by WAL summarization off", func(t *testing.T) {+ prereqs := createNextScheduledBackupsPrereqs(t, postgresql_physical.BackupTypeFullAndIncremental)+ saveNextScheduledBackupsTestConfig(t, prereqs, &prereqs.storage.ID)++ full := createNextScheduledBackupsTestFull(+ t, prereqs, physical_enums.PhysicalBackupStatusCompleted, time.Now().UTC().Add(-2*time.Hour))+ brokenIncremental := createNextScheduledBackupsTestIncremental(+ t, prereqs, full.ID, physical_enums.PhysicalBackupStatusChainBroken, time.Now().UTC().Add(-time.Hour))+ brokenIncremental.ErrorReason = new(physical_enums.PhysicalBackupErrorSummarizerOff)+ require.NoError(t, physical_repositories.GetIncrementalBackupRepository().Save(brokenIncremental))++ response := getNextScheduledBackups(t, prereqs, prereqs.user.Token)++ assert.NotNil(t, response.NextFullBackup)+ assert.Nil(t, response.NextIncrementalBackup)+ })++ t.Run("no completed full among the newest attempts", func(t *testing.T) {+ prereqs := createNextScheduledBackupsPrereqs(t, postgresql_physical.BackupTypeFullAndIncremental)+ saveNextScheduledBackupsTestConfig(t, prereqs, &prereqs.storage.ID)++ createNextScheduledBackupsTestFull(+ t, prereqs, physical_enums.PhysicalBackupStatusError, time.Now().UTC().Add(-2*time.Hour))++ response := getNextScheduledBackups(t, prereqs, prereqs.user.Token)++ assert.NotNil(t, response.NextFullBackup)+ assert.Nil(t, response.NextIncrementalBackup)+ })+}++func Test_GetNextScheduledBackups_WhenDatabaseIsLogical_ReturnsBadRequest(t *testing.T) {+ prereqs := createPhysicalControllerPrereqs(t)+ logicalDatabase := databases.CreateTestDatabase(prereqs.workspace.ID, prereqs.storage, prereqs.notifier)+ t.Cleanup(func() { databases.RemoveTestDatabase(t.Context(), logicalDatabase) })++ response := test_utils.MakeGetRequest(t, prereqs.router,+ "/api/v1/backups/physical/database/"+logicalDatabase.ID.String()+"/next-backups",+ "Bearer "+prereqs.user.Token, http.StatusBadRequest)++ assert.Contains(t, string(response.Body), "logical backups")+}++func Test_GetNextScheduledBackups_PermissionsEnforced(t *testing.T) {+ prereqs := createPhysicalControllerPrereqs(t)+ saveNextScheduledBackupsTestConfig(t, prereqs, &prereqs.storage.ID)++ nextBackupsURL := "/api/v1/backups/physical/database/" + prereqs.database.ID.String() + "/next-backups"++ runRolePermissionMatrix(t, prereqs, false, http.StatusOK, func(authHeader string) int {+ return workspaces_testing.MakeAPIRequest(prereqs.router, "GET", nextBackupsURL, authHeader, nil).Code+ })++ nonMember := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)+ response := test_utils.MakeGetRequest(t, prereqs.router, nextBackupsURL,+ "Bearer "+nonMember.Token, http.StatusBadRequest)+ assert.Contains(t, string(response.Body), "insufficient permissions")+ assert.NotContains(t, string(response.Body), "nextFullBackup")+}++func Test_GetNextScheduledBackups_WhenRequestIsUnauthenticated_ReturnsUnauthorized(t *testing.T) {+ router := newPhysicalControllerRouter()++ test_utils.MakeGetRequest(t, router,+ "/api/v1/backups/physical/database/"+uuid.NewString()+"/next-backups",+ "", http.StatusUnauthorized)+}++func createNextScheduledBackupsPrereqs(+ t *testing.T,+ backupType postgresql_physical.BackupType,+) *physicalControllerPrereqs {+ t.Helper()++ prereqs := createPhysicalControllerPrereqs(t)++ port, err := strconv.Atoi(config.GetEnv().TestPhysicalPostgres17Port)+ require.NoError(t, err)++ database := databases.CreateTestPhysicalPostgresDatabaseWithType(+ config.GetEnv().TestLocalhost, port, prereqs.workspace.ID, prereqs.notifier, "17", backupType)+ t.Cleanup(func() {+ physical_testing.DeleteAllPhysicalCatalogForDatabase(t, database.ID)+ databases.RemoveTestDatabase(t.Context(), database)+ })++ prereqs.database = database++ return prereqs+}++func saveNextScheduledBackupsTestConfig(+ t *testing.T,+ prereqs *physicalControllerPrereqs,+ storageID *uuid.UUID,+) *backups_config_physical.PhysicalBackupConfig {+ t.Helper()++ configService := backups_config_physical.GetBackupConfigService()++ backupConfig, err := configService.GetBackupConfigByDbId(prereqs.database.ID)+ require.NoError(t, err)++ backupConfig.IsBackupsEnabled = true+ backupConfig.StorageID = storageID+ backupConfig.Storage = nil+ backupConfig.FullBackupInterval = intervals.Interval{+ Type: intervals.IntervalWeekly,+ TimeOfDay: new("03:00"),+ Weekday: new(int(time.Now().UTC().AddDate(0, 0, 3).Weekday())),+ }+ if backupConfig.PostgresqlPhysical.BackupType != postgresql_physical.BackupTypeFullOnly {+ backupConfig.IncrementalBackupInterval = intervals.Interval{Type: intervals.IntervalHourly}+ }++ savedConfig, err := configService.SaveBackupConfig(t.Context(), backupConfig)+ require.NoError(t, err)++ return savedConfig+}++func createNextScheduledBackupsTestFull(+ t *testing.T,+ prereqs *physicalControllerPrereqs,+ status physical_enums.PhysicalBackupStatus,+ createdAt time.Time,+) *physical_models.PhysicalFullBackup {+ t.Helper()++ full := physical_testing.NewTestCompletedFullBackup(+ prereqs.database.ID, prereqs.storage.ID, 1, walmath.LSN(0), walmath.LSN(segmentBytes))+ full.Status = status+ full.CreatedAt = createdAt++ return physical_testing.CreateTestFullBackup(t, full)+}++func createNextScheduledBackupsTestIncremental(+ t *testing.T,+ prereqs *physicalControllerPrereqs,+ rootFullBackupID uuid.UUID,+ status physical_enums.PhysicalBackupStatus,+ createdAt time.Time,+) *physical_models.PhysicalIncrementalBackup {+ t.Helper()++ incremental := physical_testing.NewTestCompletedIncrementalBackup(+ prereqs.database.ID, prereqs.storage.ID, rootFullBackupID, nil, 1,+ walmath.LSN(segmentBytes), walmath.LSN(2*segmentBytes))+ incremental.Status = status+ incremental.CreatedAt = createdAt++ return physical_testing.CreateTestIncrementalBackup(t, incremental)+}++func getNextScheduledBackups(+ t *testing.T,+ prereqs *physicalControllerPrereqs,+ token string,+) *backups_dto_physical.GetNextScheduledBackupsResponse {+ t.Helper()++ var response backups_dto_physical.GetNextScheduledBackupsResponse+ test_utils.MakeGetRequestAndUnmarshal(t, prereqs.router,+ "/api/v1/backups/physical/database/"+prereqs.database.ID.String()+"/next-backups",+ "Bearer "+token, http.StatusOK, &response)++ return &response+}++func assertNoNextScheduledBackups(+ t *testing.T,+ response *backups_dto_physical.GetNextScheduledBackupsResponse,+) {+ t.Helper()++ assert.Nil(t, response.NextFullBackup)+ assert.Nil(t, response.NextIncrementalBackup)+}diff --git a/backend/internal/features/backups/backups/dto/logical/dto.go b/backend/internal/features/backups/backups/dto/logical/dto.goindex f6c37e31..18f45cb4 100644--- a/backend/internal/features/backups/backups/dto/logical/dto.go+++ b/backend/internal/features/backups/backups/dto/logical/dto.go@@ -8,6 +8,7 @@ import (backups_core_logical "databasus-backend/internal/features/backups/backups/core/logical""databasus-backend/internal/features/backups/backups/encryption"+ "databasus-backend/internal/features/intervals")type GetBackupsRequest struct {@@ -25,6 +26,10 @@ type GetBackupsResponse struct {Offset int `json:"offset"`}+type GetNextScheduledBackupResponse struct {+ NextBackup *intervals.NextTrigger `json:"nextBackup"`+}+type DecryptionReaderCloser struct {*encryption.DecryptionReaderBaseReader io.ReadCloserdiff --git a/backend/internal/features/backups/backups/dto/physical/dto.go b/backend/internal/features/backups/backups/dto/physical/dto.goindex fd3bae6b..b6bf12ec 100644--- a/backend/internal/features/backups/backups/dto/physical/dto.go+++ b/backend/internal/features/backups/backups/dto/physical/dto.go@@ -6,6 +6,7 @@ import ("github.com/google/uuid"physical_enums "databasus-backend/internal/features/backups/backups/core/physical/enums"+ "databasus-backend/internal/features/intervals")// PhysicalBackupListItem is one row of the flat physical-backup list: a FULL, an@@ -90,3 +91,8 @@ type GenerateRestoreTokenResponse struct {Token string `json:"token"`URL string `json:"url"`}++type GetNextScheduledBackupsResponse struct {+ NextFullBackup *intervals.NextTrigger `json:"nextFullBackup"`+ NextIncrementalBackup *intervals.NextTrigger `json:"nextIncrementalBackup"`+}diff --git a/backend/internal/features/backups/backups/services/di.go b/backend/internal/features/backups/backups/services/di.goindex 09dd3911..aa041c54 100644--- a/backend/internal/features/backups/backups/services/di.go+++ b/backend/internal/features/backups/backups/services/di.go@@ -61,6 +61,7 @@ var physicalBackupService = &PhysicalBackupService{physical_repositories.GetWalSegmentRepository(),physical_repositories.GetInFlightBackupRepository(),backuping_physical.GetPhysicalBackupCanceller(),+ backuping_physical.GetPhysicalBackupsScheduler(),backups_download.GetRestoreStreamWriter(),backups_download.GetRestoreTokenService(),encryption_secrets.GetSecretKeyService(),diff --git a/backend/internal/features/backups/backups/services/logical_service.go b/backend/internal/features/backups/backups/services/logical_service.goindex b5f55131..2645f70b 100644--- a/backend/internal/features/backups/backups/services/logical_service.go+++ b/backend/internal/features/backups/backups/services/logical_service.go@@ -129,6 +129,28 @@ func (s *LogicalBackupService) MakeBackupWithAuth(return nil}+func (s *LogicalBackupService) GetNextScheduledBackup(+ ctx context.Context,+ user *users_models.User,+ databaseID uuid.UUID,+) (*backups_dto_logical.GetNextScheduledBackupResponse, error) {+ database, err := s.databaseService.GetDatabase(ctx, user, databaseID)+ if err != nil {+ return nil, err+ }++ if database.Type == databases.DatabaseTypePostgresPhysical {+ return nil, errors.New("database uses physical backups")+ }++ nextBackup, err := s.backupSchedulerService.GetNextScheduledBackup(databaseID, time.Now().UTC())+ if err != nil {+ return nil, err+ }++ return &backups_dto_logical.GetNextScheduledBackupResponse{NextBackup: nextBackup}, nil+}+func (s *LogicalBackupService) GetBackups(ctx context.Context,user *users_models.User,diff --git a/backend/internal/features/backups/backups/services/physical_service.go b/backend/internal/features/backups/backups/services/physical_service.goindex 21c74122..60a7157d 100644--- a/backend/internal/features/backups/backups/services/physical_service.go+++ b/backend/internal/features/backups/backups/services/physical_service.go@@ -63,6 +63,7 @@ type PhysicalBackupService struct {walSegmentRepository *physical_repositories.PhysicalWalSegmentRepositoryinFlightBackupRepository *physical_repositories.PhysicalInFlightBackupRepositorycanceller *backuping_physical.PhysicalBackupCanceller+ scheduler *backuping_physical.PhysicalBackupsSchedulerrestoreStreamWriter *restore_stream.WriterrestoreTokenService *restore_token.ServicesecretKeyService *encryption_secrets.SecretKeyService@@ -70,6 +71,32 @@ type PhysicalBackupService struct {logger *slog.Logger}+func (s *PhysicalBackupService) GetNextScheduledBackups(+ ctx context.Context,+ user *users_models.User,+ databaseID uuid.UUID,+) (*backups_dto_physical.GetNextScheduledBackupsResponse, error) {+ database, err := s.databaseService.GetDatabase(ctx, user, databaseID)+ if err != nil {+ return nil, err+ }++ if database.Type != databases.DatabaseTypePostgresPhysical {+ return nil, errors.New("database uses logical backups")+ }++ nextFullBackup, nextIncrementalBackup, err := s.scheduler.GetNextScheduledBackups(+ databaseID, time.Now().UTC())+ if err != nil {+ return nil, err+ }++ return &backups_dto_physical.GetNextScheduledBackupsResponse{+ NextFullBackup: nextFullBackup,+ NextIncrementalBackup: nextIncrementalBackup,+ }, nil+}+// GetBackups returns one page of a database's backups — FULLs, incrementals and// WAL ranges of consecutive committed segments — as one flat list sorted// newest-first. It pages by keyset cursor rather than offset because the newestdiff --git a/backend/internal/features/backups/config/logical/service.go b/backend/internal/features/backups/config/logical/service.goindex f4f1bbef..822b1b90 100644--- a/backend/internal/features/backups/config/logical/service.go+++ b/backend/internal/features/backups/config/logical/service.go@@ -145,6 +145,14 @@ func (s *BackupConfigService) GetBackupConfigByDbId(return config, nil}+// FindBackupConfigByDbId returns nil when the database has no saved backup config,+// unlike GetBackupConfigByDbId, which creates a default one.+func (s *BackupConfigService) FindBackupConfigByDbId(+ databaseID uuid.UUID,+) (*LogicalBackupConfig, error) {+ return s.backupConfigRepository.FindByDatabaseID(databaseID)+}+func (s *BackupConfigService) IsStorageInUse(ctx context.Context,user *users_models.User,diff --git a/backend/internal/features/backups/config/physical/service.go b/backend/internal/features/backups/config/physical/service.goindex 0d5d1fe3..8495adb8 100644--- a/backend/internal/features/backups/config/physical/service.go+++ b/backend/internal/features/backups/config/physical/service.go@@ -189,6 +189,14 @@ func (s *BackupConfigService) GetBackupConfigByDbId(return config, nil}+// FindBackupConfigByDbId returns nil when the database has no saved backup config,+// unlike GetBackupConfigByDbId, which creates a default one.+func (s *BackupConfigService) FindBackupConfigByDbId(+ databaseID uuid.UUID,+) (*PhysicalBackupConfig, error) {+ return s.backupConfigRepository.FindByDatabaseID(databaseID)+}+func (s *BackupConfigService) IsStorageInUse(ctx context.Context,user *users_models.User,diff --git a/backend/internal/features/intervals/dto.go b/backend/internal/features/intervals/dto.gonew file mode 100644index 00000000..83d68a6a--- /dev/null+++ b/backend/internal/features/intervals/dto.go@@ -0,0 +1,10 @@+package intervals++import "time"++// NextTrigger is the moment the scheduler will first treat a backup as due.+// When IsDue is set, the backup is due already and ScheduledAt is the moment of the check.+type NextTrigger struct {+ ScheduledAt time.Time `json:"scheduledAt"`+ IsDue bool `json:"isDue"`+}diff --git a/backend/internal/features/intervals/model.go b/backend/internal/features/intervals/model.goindex bdbb4c8c..daa2a59f 100644--- a/backend/internal/features/intervals/model.go+++ b/backend/internal/features/intervals/model.go@@ -91,29 +91,30 @@ func (i *Interval) ShouldTriggerBackup(now time.Time, lastBackupTime *time.Time)}}-// NextTriggerTime computes the next time a backup should trigger based on the interval and last backup time.-// Returns nil when a backup is due immediately (no previous backup exists).-func (i *Interval) NextTriggerTime(now time.Time, lastBackupTime *time.Time) *time.Time {- if lastBackupTime == nil {+// GetNextTrigger reports when the scheduler will first treat a backup as due.+// Returns nil when the interval cannot be evaluated. Passing Validate is what lets+// the next*Trigger helpers dereference fields and ignore parse errors.+func (i *Interval) GetNextTrigger(now time.Time, lastBackupTime *time.Time) *NextTrigger {+ if i.Validate() != nil {return nil}+ if i.ShouldTriggerBackup(now, lastBackupTime) {+ return &NextTrigger{ScheduledAt: now, IsDue: true}+ }+switch i.Type {case IntervalHourly:- next := lastBackupTime.Add(time.Hour)- return &next+ return &NextTrigger{ScheduledAt: lastBackupTime.Add(time.Hour)}case IntervalDaily:- next := i.nextDailyTrigger(now)- return &next+ return &NextTrigger{ScheduledAt: i.nextDailyTrigger(now)}case IntervalWeekly:- next := i.nextWeeklyTrigger(now)- return &next+ return &NextTrigger{ScheduledAt: i.nextWeeklyTrigger(now)}case IntervalMonthly:- next := i.nextMonthlyTrigger(now)- return &next+ return &NextTrigger{ScheduledAt: i.nextMonthlyTrigger(now)}case IntervalCron:return i.nextCronTrigger(*lastBackupTime)@@ -153,117 +154,89 @@ func (i *Interval) Copy() Interval {}}-// daily trigger: honour the TimeOfDay slot and catch up the previous one+// A missed slot is caught up: the backup fires on the first check after it.func (i *Interval) shouldTriggerDaily(now, lastBackup time.Time) bool {if i.TimeOfDay == nil {return !isSameDay(lastBackup, now)}- t, err := time.Parse("15:04", *i.TimeOfDay)- if err != nil {+ todaySlot, isParsed := i.getTodaySlot(now)+ if !isParsed {return false // malformed ⇒ play safe}- // Today's scheduled slot (todayTgt)- todayTgt := time.Date(- now.Year(), now.Month(), now.Day(),- t.Hour(), t.Minute(), 0, 0, now.Location(),- )-- // The last scheduled slot that should already have happened- var lastScheduled time.Time- if now.Before(todayTgt) {- lastScheduled = todayTgt.AddDate(0, 0, -1)- } else {- lastScheduled = todayTgt+ latestSlot := todaySlot+ if now.Before(todaySlot) {+ latestSlot = todaySlot.AddDate(0, 0, -1)}- // Fire when we are past that slot AND no backup has been taken since it- return (now.After(lastScheduled) || now.Equal(lastScheduled)) &&- lastBackup.Before(lastScheduled)+ return !now.Before(latestSlot) && lastBackup.Before(latestSlot)}-// weekly trigger: on specified weekday/calendar week, otherwise ≥7 days+// Only this week's slot counts, so a slot missed in an earlier week is not caught up.+// Without a weekday the interval is a plain 7 days.func (i *Interval) shouldTriggerWeekly(now, lastBackup time.Time) bool {- if i.Weekday != nil {- targetWd := time.Weekday(*i.Weekday)-- // Calculate the target datetime for this week- startOfWeek := getStartOfWeek(now)-- // Convert Go weekday to days from Monday: Sunday=6, Monday=0, Tuesday=1, ..., Saturday=5- var daysFromMonday int- if targetWd == time.Sunday {- daysFromMonday = 6- } else {- daysFromMonday = int(targetWd) - 1- }+ if i.Weekday == nil {+ return now.Sub(lastBackup) >= 7*24*time.Hour+ }- targetThisWeek := startOfWeek.AddDate(0, 0, daysFromMonday)-- if i.TimeOfDay != nil {- t, err := time.Parse("15:04", *i.TimeOfDay)- if err == nil {- targetThisWeek = time.Date(- targetThisWeek.Year(),- targetThisWeek.Month(),- targetThisWeek.Day(),- t.Hour(),- t.Minute(),- 0,- 0,- targetThisWeek.Location(),- )- }- }+ thisWeekSlot := i.getThisWeekSlot(now)- // If current time is at or after the target time this week- // and no backup has been made at or after the target time, trigger- if now.After(targetThisWeek) || now.Equal(targetThisWeek) {- return lastBackup.Before(targetThisWeek)- }+ return !now.Before(thisWeekSlot) && lastBackup.Before(thisWeekSlot)+}- return false+// Only this month's slot counts, so a slot missed in an earlier month is not caught up.+// A day the month lacks overflows into the next month and is never reached, so that+// month gets no backup. Without a day of month, the first check of a new month fires.+func (i *Interval) shouldTriggerMonthly(now, lastBackup time.Time) bool {+ if i.DayOfMonth == nil {+ return lastBackup.Before(getStartOfMonth(now))}- // no Weekday: generic 7-day interval- return now.Sub(lastBackup) >= 7*24*time.Hour+ thisMonthSlot := i.getMonthSlot(now)++ return !now.Before(thisMonthSlot) && lastBackup.Before(thisMonthSlot)}-// monthly trigger: on specified day/calendar month, otherwise next calendar month-func (i *Interval) shouldTriggerMonthly(now, lastBackup time.Time) bool {- if i.DayOfMonth != nil {- day := *i.DayOfMonth-- // Calculate the target datetime for this month- targetThisMonth := time.Date(now.Year(), now.Month(), day, 0, 0, 0, 0, now.Location())-- if i.TimeOfDay != nil {- t, err := time.Parse("15:04", *i.TimeOfDay)- if err == nil {- targetThisMonth = time.Date(- targetThisMonth.Year(),- targetThisMonth.Month(),- targetThisMonth.Day(),- t.Hour(),- t.Minute(),- 0,- 0,- targetThisMonth.Location(),- )- }- }+func (i *Interval) getTodaySlot(now time.Time) (time.Time, bool) {+ t, err := time.Parse("15:04", *i.TimeOfDay)+ if err != nil {+ return time.Time{}, false+ }- // If current time is at or after the target time this month- // and no backup has been made at or after the target time, trigger- if now.After(targetThisMonth) || now.Equal(targetThisMonth) {- return lastBackup.Before(targetThisMonth)- }+ return time.Date(now.Year(), now.Month(), now.Day(), t.Hour(), t.Minute(), 0, 0, now.Location()), true+}- return false+// The weekly slot is at midnight when TimeOfDay is missing or malformed.+// Weekday 7 lands on Sunday like 0.+func (i *Interval) getThisWeekSlot(now time.Time) time.Time {+ weekday := time.Weekday(*i.Weekday)++ daysFromMonday := int(weekday) - 1+ if weekday == time.Sunday {+ daysFromMonday = 6+ }++ return i.atTimeOfDay(getStartOfWeek(now).AddDate(0, 0, daysFromMonday))+}++// The monthly slot is at midnight when TimeOfDay is missing or malformed. A day the+// month lacks is normalized into the following month, like time.Date does.+func (i *Interval) getMonthSlot(month time.Time) time.Time {+ return i.atTimeOfDay(time.Date(month.Year(), month.Month(), *i.DayOfMonth, 0, 0, 0, 0, month.Location()))+}++func (i *Interval) atTimeOfDay(day time.Time) time.Time {+ if i.TimeOfDay == nil {+ return day+ }++ t, err := time.Parse("15:04", *i.TimeOfDay)+ if err != nil {+ return day}- // no DayOfMonth: if we're in a new calendar month- return lastBackup.Before(getStartOfMonth(now))++ return time.Date(day.Year(), day.Month(), day.Day(), t.Hour(), t.Minute(), 0, 0, day.Location())}func isSameDay(a, b time.Time) bool {@@ -284,7 +257,6 @@ func getStartOfMonth(t time.Time) time.Time {return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())}-// cron trigger: check if we've passed a scheduled cron time since last backupfunc (i *Interval) shouldTriggerCron(now, lastBackup time.Time) bool {if i.CronExpression == nil || *i.CronExpression == "" {return false@@ -296,23 +268,11 @@ func (i *Interval) shouldTriggerCron(now, lastBackup time.Time) bool {return false}- // Find the next scheduled time after the last backup- nextAfterLastBackup := schedule.Next(lastBackup)-- // If we're at or past that next scheduled time, trigger- return now.After(nextAfterLastBackup) || now.Equal(nextAfterLastBackup)+ return !now.Before(schedule.Next(lastBackup))}func (i *Interval) nextDailyTrigger(now time.Time) time.Time {- t, err := time.Parse("15:04", *i.TimeOfDay)- if err != nil {- return now- }-- todaySlot := time.Date(- now.Year(), now.Month(), now.Day(),- t.Hour(), t.Minute(), 0, 0, now.Location(),- )+ todaySlot, _ := i.getTodaySlot(now)if now.Before(todaySlot) {return todaySlot@@ -322,78 +282,34 @@ func (i *Interval) nextDailyTrigger(now time.Time) time.Time {}func (i *Interval) nextWeeklyTrigger(now time.Time) time.Time {- targetWd := time.Weekday(0)- if i.Weekday != nil {- targetWd = time.Weekday(*i.Weekday)- }-- startOfWeek := getStartOfWeek(now)-- var daysFromMonday int- if targetWd == time.Sunday {- daysFromMonday = 6- } else {- daysFromMonday = int(targetWd) - 1- }-- targetThisWeek := startOfWeek.AddDate(0, 0, daysFromMonday)-- if i.TimeOfDay != nil {- t, err := time.Parse("15:04", *i.TimeOfDay)- if err == nil {- targetThisWeek = time.Date(- targetThisWeek.Year(), targetThisWeek.Month(), targetThisWeek.Day(),- t.Hour(), t.Minute(), 0, 0, targetThisWeek.Location(),- )- }- }+ thisWeekSlot := i.getThisWeekSlot(now)- if now.Before(targetThisWeek) {- return targetThisWeek+ if now.Before(thisWeekSlot) {+ return thisWeekSlot}- return targetThisWeek.AddDate(0, 0, 7)+ return thisWeekSlot.AddDate(0, 0, 7)}+// Months without the configured day are skipped, as in shouldTriggerMonthly.func (i *Interval) nextMonthlyTrigger(now time.Time) time.Time {- day := 1- if i.DayOfMonth != nil {- day = *i.DayOfMonth- }+ for month := getStartOfMonth(now); ; month = month.AddDate(0, 1, 0) {+ monthSlot := i.getMonthSlot(month)- targetThisMonth := time.Date(now.Year(), now.Month(), day, 0, 0, 0, 0, now.Location())-- if i.TimeOfDay != nil {- t, err := time.Parse("15:04", *i.TimeOfDay)- if err == nil {- targetThisMonth = time.Date(- targetThisMonth.Year(), targetThisMonth.Month(), targetThisMonth.Day(),- t.Hour(), t.Minute(), 0, 0, targetThisMonth.Location(),- )+ if monthSlot.Month() == month.Month() && monthSlot.After(now) {+ return monthSlot}}-- if now.Before(targetThisMonth) {- return targetThisMonth- }-- return targetThisMonth.AddDate(0, 1, 0)}-func (i *Interval) nextCronTrigger(lastBackup time.Time) *time.Time {- if i.CronExpression == nil || *i.CronExpression == "" {- return nil- }-+func (i *Interval) nextCronTrigger(lastBackup time.Time) *NextTrigger {parser := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow)schedule, err := parser.Parse(*i.CronExpression)if err != nil {return nil}- next := schedule.Next(lastBackup)-- return &next+ return &NextTrigger{ScheduledAt: schedule.Next(lastBackup)}}func (i *Interval) validateCronExpression(expr string) error {diff --git a/backend/internal/features/intervals/model_test.go b/backend/internal/features/intervals/model_test.goindex e0e4173e..ed9ac6e3 100644--- a/backend/internal/features/intervals/model_test.go+++ b/backend/internal/features/intervals/model_test.go@@ -795,259 +795,310 @@ func TestInterval_Validate(t *testing.T) {})}-func TestInterval_NextTriggerTime_NilLastBackup(t *testing.T) {- now := time.Date(2024, 1, 15, 12, 0, 0, 0, time.UTC)-- t.Run("Hourly with nil lastBackup returns nil", func(t *testing.T) {- interval := &Interval{Type: IntervalHourly}- result := interval.NextTriggerTime(now, nil)- assert.Nil(t, result)- })-- t.Run("Daily with nil lastBackup returns nil", func(t *testing.T) {- timeOfDay := "09:00"- interval := &Interval{Type: IntervalDaily, TimeOfDay: &timeOfDay}- result := interval.NextTriggerTime(now, nil)- assert.Nil(t, result)- })-- t.Run("Weekly with nil lastBackup returns nil", func(t *testing.T) {- timeOfDay := "15:00"- weekday := 3- interval := &Interval{- Type: IntervalWeekly,- TimeOfDay: &timeOfDay,- Weekday: &weekday,- }- result := interval.NextTriggerTime(now, nil)- assert.Nil(t, result)- })-- t.Run("Monthly with nil lastBackup returns nil", func(t *testing.T) {- timeOfDay := "08:00"- dayOfMonth := 10- interval := &Interval{- Type: IntervalMonthly,- TimeOfDay: &timeOfDay,- DayOfMonth: &dayOfMonth,- }- result := interval.NextTriggerTime(now, nil)- assert.Nil(t, result)- })-- t.Run("Cron with nil lastBackup returns nil", func(t *testing.T) {- cronExpr := "0 2 * * *"- interval := &Interval{Type: IntervalCron, CronExpression: &cronExpr}- result := interval.NextTriggerTime(now, nil)- assert.Nil(t, result)- })-}--func TestInterval_NextTriggerTime_Hourly(t *testing.T) {- interval := &Interval{Type: IntervalHourly}- now := time.Date(2024, 1, 15, 12, 0, 0, 0, time.UTC)-- t.Run("Returns lastBackup + 1 hour", func(t *testing.T) {- lastBackup := time.Date(2024, 1, 15, 11, 0, 0, 0, time.UTC)- result := interval.NextTriggerTime(now, &lastBackup)-- assert.NotNil(t, result)- assert.Equal(t, time.Date(2024, 1, 15, 12, 0, 0, 0, time.UTC), *result)- })-- t.Run("Returns future time when last backup was recent", func(t *testing.T) {- lastBackup := time.Date(2024, 1, 15, 11, 30, 0, 0, time.UTC)- result := interval.NextTriggerTime(now, &lastBackup)-- assert.NotNil(t, result)- assert.Equal(t, time.Date(2024, 1, 15, 12, 30, 0, 0, time.UTC), *result)- })-}--func TestInterval_NextTriggerTime_Daily(t *testing.T) {- timeOfDay := "09:00"- interval := &Interval{Type: IntervalDaily, TimeOfDay: &timeOfDay}-- t.Run("Before today's slot: returns today's slot", func(t *testing.T) {- now := time.Date(2024, 1, 15, 8, 0, 0, 0, time.UTC)- lastBackup := time.Date(2024, 1, 14, 9, 0, 0, 0, time.UTC)- result := interval.NextTriggerTime(now, &lastBackup)-- assert.NotNil(t, result)- assert.Equal(t, time.Date(2024, 1, 15, 9, 0, 0, 0, time.UTC), *result)- })-- t.Run("After today's slot: returns tomorrow's slot", func(t *testing.T) {- now := time.Date(2024, 1, 15, 10, 0, 0, 0, time.UTC)- lastBackup := time.Date(2024, 1, 15, 9, 0, 0, 0, time.UTC)- result := interval.NextTriggerTime(now, &lastBackup)-- assert.NotNil(t, result)- assert.Equal(t, time.Date(2024, 1, 16, 9, 0, 0, 0, time.UTC), *result)- })-- t.Run("Exactly at today's slot: returns tomorrow's slot", func(t *testing.T) {- now := time.Date(2024, 1, 15, 9, 0, 0, 0, time.UTC)- lastBackup := time.Date(2024, 1, 14, 9, 0, 0, 0, time.UTC)- result := interval.NextTriggerTime(now, &lastBackup)-- assert.NotNil(t, result)- assert.Equal(t, time.Date(2024, 1, 16, 9, 0, 0, 0, time.UTC), *result)- })-}--func TestInterval_NextTriggerTime_Weekly(t *testing.T) {- timeOfDay := "15:00"- weekday := 3 // Wednesday- interval := &Interval{- Type: IntervalWeekly,- TimeOfDay: &timeOfDay,- Weekday: &weekday,+func Test_GetNextTrigger_ForEveryIntervalType_MatchesShouldTriggerBackup(t *testing.T) {+ testCases := []struct {+ name string+ interval Interval+ now time.Time+ lastBackupTime *time.Time+ nextScheduledAt time.Time+ isDueNow bool+ }{+ {+ name: "Hourly with a recent backup",+ interval: Interval{Type: IntervalHourly},+ now: time.Date(2026, 1, 15, 12, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 1, 15, 11, 30, 15, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 1, 15, 12, 30, 15, 0, time.UTC),+ },+ {+ name: "Hourly with an hour elapsed",+ interval: Interval{Type: IntervalHourly},+ now: time.Date(2026, 1, 15, 12, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 1, 15, 11, 0, 0, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 1, 15, 12, 0, 0, 0, time.UTC),+ isDueNow: true,+ },+ {+ name: "Daily without any backup",+ interval: Interval{Type: IntervalDaily, TimeOfDay: new("03:00")},+ now: time.Date(2026, 1, 15, 1, 0, 0, 0, time.UTC),+ nextScheduledAt: time.Date(2026, 1, 15, 1, 0, 0, 0, time.UTC),+ isDueNow: true,+ },+ {+ name: "Daily before today's slot",+ interval: Interval{Type: IntervalDaily, TimeOfDay: new("03:00")},+ now: time.Date(2026, 1, 15, 1, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 1, 14, 3, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 1, 15, 3, 0, 0, 0, time.UTC),+ },+ {+ name: "Daily after today's backup",+ interval: Interval{Type: IntervalDaily, TimeOfDay: new("03:00")},+ now: time.Date(2026, 1, 15, 10, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 1, 15, 3, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 1, 16, 3, 0, 0, 0, time.UTC),+ },+ {+ name: "Daily with a missed slot",+ interval: Interval{Type: IntervalDaily, TimeOfDay: new("03:00")},+ now: time.Date(2026, 1, 15, 10, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 1, 13, 3, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 1, 15, 10, 0, 0, 0, time.UTC),+ isDueNow: true,+ },+ {+ name: "Daily exactly at the slot",+ interval: Interval{Type: IntervalDaily, TimeOfDay: new("03:00")},+ now: time.Date(2026, 1, 15, 3, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 1, 14, 3, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 1, 15, 3, 0, 0, 0, time.UTC),+ isDueNow: true,+ },+ {+ name: "Weekly before this week's slot",+ interval: Interval{+ Type: IntervalWeekly,+ TimeOfDay: new("03:00"),+ Weekday: new(int(time.Wednesday)),+ },+ now: time.Date(2026, 1, 13, 10, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 1, 7, 3, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 1, 14, 3, 0, 0, 0, time.UTC),+ },+ {+ name: "Weekly with a slot missed in an earlier week",+ interval: Interval{+ Type: IntervalWeekly,+ TimeOfDay: new("03:00"),+ Weekday: new(int(time.Wednesday)),+ },+ now: time.Date(2026, 1, 13, 10, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2025, 12, 24, 3, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 1, 14, 3, 0, 0, 0, time.UTC),+ },+ {+ name: "Weekly after this week's backup",+ interval: Interval{+ Type: IntervalWeekly,+ TimeOfDay: new("03:00"),+ Weekday: new(int(time.Wednesday)),+ },+ now: time.Date(2026, 1, 15, 10, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 1, 14, 3, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 1, 21, 3, 0, 0, 0, time.UTC),+ },+ {+ name: "Weekly with this week's slot missed",+ interval: Interval{+ Type: IntervalWeekly,+ TimeOfDay: new("03:00"),+ Weekday: new(int(time.Wednesday)),+ },+ now: time.Date(2026, 1, 15, 10, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 1, 7, 3, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 1, 15, 10, 0, 0, 0, time.UTC),+ isDueNow: true,+ },+ {+ name: "Weekly on Sunday written as 7",+ interval: Interval{+ Type: IntervalWeekly,+ TimeOfDay: new("03:00"),+ Weekday: new(7),+ },+ now: time.Date(2026, 1, 13, 10, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 1, 11, 3, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 1, 18, 3, 0, 0, 0, time.UTC),+ },+ {+ name: "Monthly before this month's slot",+ interval: Interval{+ Type: IntervalMonthly,+ TimeOfDay: new("08:00"),+ DayOfMonth: new(10),+ },+ now: time.Date(2026, 1, 5, 10, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2025, 12, 10, 8, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 1, 10, 8, 0, 0, 0, time.UTC),+ },+ {+ name: "Monthly after this month's backup",+ interval: Interval{+ Type: IntervalMonthly,+ TimeOfDay: new("08:00"),+ DayOfMonth: new(10),+ },+ now: time.Date(2026, 1, 15, 10, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 1, 10, 8, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 2, 10, 8, 0, 0, 0, time.UTC),+ },+ {+ name: "Monthly with this month's slot missed",+ interval: Interval{+ Type: IntervalMonthly,+ TimeOfDay: new("08:00"),+ DayOfMonth: new(10),+ },+ now: time.Date(2026, 1, 15, 10, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2025, 12, 10, 8, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 1, 15, 10, 0, 0, 0, time.UTC),+ isDueNow: true,+ },+ {+ name: "Monthly on day 31 skips February",+ interval: Interval{+ Type: IntervalMonthly,+ TimeOfDay: new("03:00"),+ DayOfMonth: new(31),+ },+ now: time.Date(2026, 1, 31, 10, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 1, 31, 3, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 3, 31, 3, 0, 0, 0, time.UTC),+ },+ {+ name: "Monthly on day 31 skips a 30-day month",+ interval: Interval{+ Type: IntervalMonthly,+ TimeOfDay: new("03:00"),+ DayOfMonth: new(31),+ },+ now: time.Date(2026, 4, 10, 10, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 3, 31, 3, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 5, 31, 3, 0, 0, 0, time.UTC),+ },+ {+ name: "Monthly on day 30 skips February",+ interval: Interval{+ Type: IntervalMonthly,+ TimeOfDay: new("03:00"),+ DayOfMonth: new(30),+ },+ now: time.Date(2026, 2, 1, 10, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 1, 30, 3, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 3, 30, 3, 0, 0, 0, time.UTC),+ },+ {+ name: "Monthly on day 29 skips February outside a leap year",+ interval: Interval{+ Type: IntervalMonthly,+ TimeOfDay: new("03:00"),+ DayOfMonth: new(29),+ },+ now: time.Date(2026, 2, 1, 10, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 1, 29, 3, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 3, 29, 3, 0, 0, 0, time.UTC),+ },+ {+ name: "Monthly on day 29 keeps February in a leap year",+ interval: Interval{+ Type: IntervalMonthly,+ TimeOfDay: new("03:00"),+ DayOfMonth: new(29),+ },+ now: time.Date(2028, 2, 1, 10, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2028, 1, 29, 3, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2028, 2, 29, 3, 0, 0, 0, time.UTC),+ },+ {+ name: "Cron before the next run",+ interval: Interval{Type: IntervalCron, CronExpression: new("0 */6 * * *")},+ now: time.Date(2026, 1, 15, 8, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 1, 15, 6, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 1, 15, 12, 0, 0, 0, time.UTC),+ },+ {+ name: "Cron with a missed run",+ interval: Interval{Type: IntervalCron, CronExpression: new("0 */6 * * *")},+ now: time.Date(2026, 1, 15, 13, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 1, 15, 6, 0, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 1, 15, 13, 0, 0, 0, time.UTC),+ isDueNow: true,+ },+ {+ name: "Cron on the 1st and 15th",+ interval: Interval{Type: IntervalCron, CronExpression: new("30 4 1,15 * *")},+ now: time.Date(2026, 1, 10, 10, 0, 0, 0, time.UTC),+ lastBackupTime: new(time.Date(2026, 1, 1, 4, 30, 20, 0, time.UTC)),+ nextScheduledAt: time.Date(2026, 1, 15, 4, 30, 0, 0, time.UTC),+ },}- t.Run("Before this week's target: returns this week's target", func(t *testing.T) {- // Tuesday Jan 16, 2024- now := time.Date(2024, 1, 16, 10, 0, 0, 0, time.UTC)- lastBackup := time.Date(2024, 1, 10, 15, 0, 0, 0, time.UTC)- result := interval.NextTriggerTime(now, &lastBackup)-- assert.NotNil(t, result)- // Wednesday Jan 17 at 15:00- assert.Equal(t, time.Date(2024, 1, 17, 15, 0, 0, 0, time.UTC), *result)- })-- t.Run("After this week's target: returns next week's target", func(t *testing.T) {- // Thursday Jan 18, 2024- now := time.Date(2024, 1, 18, 10, 0, 0, 0, time.UTC)- lastBackup := time.Date(2024, 1, 17, 15, 0, 0, 0, time.UTC)- result := interval.NextTriggerTime(now, &lastBackup)-- assert.NotNil(t, result)- // Next Wednesday Jan 24 at 15:00- assert.Equal(t, time.Date(2024, 1, 24, 15, 0, 0, 0, time.UTC), *result)- })-- t.Run("Friday interval: returns correct target", func(t *testing.T) {- fridayTimeOfDay := "00:00"- fridayWeekday := 5 // Friday- fridayInterval := &Interval{- Type: IntervalWeekly,- TimeOfDay: &fridayTimeOfDay,- Weekday: &fridayWeekday,- }+ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ require.NoError(t, testCase.interval.Validate())- // Wednesday Jan 17, 2024- now := time.Date(2024, 1, 17, 10, 0, 0, 0, time.UTC)- lastBackup := time.Date(2024, 1, 12, 0, 0, 0, 0, time.UTC)- result := fridayInterval.NextTriggerTime(now, &lastBackup)+ nextTrigger := testCase.interval.GetNextTrigger(testCase.now, testCase.lastBackupTime)- assert.NotNil(t, result)- // Friday Jan 19 at 00:00- assert.Equal(t, time.Date(2024, 1, 19, 0, 0, 0, 0, time.UTC), *result)- })+ require.NotNil(t, nextTrigger)+ assert.Equal(t, testCase.nextScheduledAt, nextTrigger.ScheduledAt)+ assert.Equal(t, testCase.isDueNow, nextTrigger.IsDue)+ assertNextTriggerMatchesShouldTriggerBackup(+ t, &testCase.interval, testCase.now, testCase.lastBackupTime, nextTrigger)+ })+ }}-func TestInterval_NextTriggerTime_Monthly(t *testing.T) {- timeOfDay := "08:00"- dayOfMonth := 10- interval := &Interval{- Type: IntervalMonthly,- TimeOfDay: &timeOfDay,- DayOfMonth: &dayOfMonth,+func Test_GetNextTrigger_WhenIntervalCannotBeEvaluated_ReturnsNil(t *testing.T) {+ testCases := []struct {+ name string+ interval Interval+ }{+ {name: "Unknown type", interval: Interval{Type: IntervalType("UNKNOWN")}},+ {name: "Daily without time of day", interval: Interval{Type: IntervalDaily}},+ {name: "Daily with malformed time of day", interval: Interval{Type: IntervalDaily, TimeOfDay: new("25:99")}},+ {name: "Weekly without weekday", interval: Interval{Type: IntervalWeekly, TimeOfDay: new("03:00")}},+ {name: "Weekly without time of day", interval: Interval{Type: IntervalWeekly, Weekday: new(3)}},+ {name: "Monthly without day of month", interval: Interval{Type: IntervalMonthly, TimeOfDay: new("03:00")}},+ {name: "Monthly with day of month out of range", interval: Interval{+ Type: IntervalMonthly,+ TimeOfDay: new("03:00"),+ DayOfMonth: new(32),+ }},+ {name: "Cron without expression", interval: Interval{Type: IntervalCron}},+ {name: "Cron with empty expression", interval: Interval{Type: IntervalCron, CronExpression: new("")}},+ {name: "Cron with unparsable expression", interval: Interval{+ Type: IntervalCron,+ CronExpression: new("invalid cron"),+ }},}- t.Run("Before this month's target: returns this month's target", func(t *testing.T) {- now := time.Date(2024, 1, 5, 10, 0, 0, 0, time.UTC)- lastBackup := time.Date(2023, 12, 10, 8, 0, 0, 0, time.UTC)- result := interval.NextTriggerTime(now, &lastBackup)-- assert.NotNil(t, result)- assert.Equal(t, time.Date(2024, 1, 10, 8, 0, 0, 0, time.UTC), *result)- })-- t.Run("After this month's target: returns next month's target", func(t *testing.T) {- now := time.Date(2024, 1, 15, 10, 0, 0, 0, time.UTC)- lastBackup := time.Date(2024, 1, 10, 8, 0, 0, 0, time.UTC)- result := interval.NextTriggerTime(now, &lastBackup)-- assert.NotNil(t, result)- assert.Equal(t, time.Date(2024, 2, 10, 8, 0, 0, 0, time.UTC), *result)- })+ now := time.Date(2026, 1, 15, 12, 0, 0, 0, time.UTC)+ lastBackupTime := time.Date(2026, 1, 10, 12, 0, 0, 0, time.UTC)- t.Run("Exactly at this month's target: returns next month's target", func(t *testing.T) {- now := time.Date(2024, 1, 10, 8, 0, 0, 0, time.UTC)- lastBackup := time.Date(2023, 12, 10, 8, 0, 0, 0, time.UTC)- result := interval.NextTriggerTime(now, &lastBackup)-- assert.NotNil(t, result)- assert.Equal(t, time.Date(2024, 2, 10, 8, 0, 0, 0, time.UTC), *result)- })+ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ assert.Nil(t, testCase.interval.GetNextTrigger(now, &lastBackupTime))+ assert.Nil(t, testCase.interval.GetNextTrigger(now, nil))+ })+ }}-func TestInterval_NextTriggerTime_Cron(t *testing.T) {- t.Run("Daily cron: returns next trigger after lastBackup", func(t *testing.T) {- cronExpr := "0 2 * * *" // Daily at 2:00 AM- interval := &Interval{Type: IntervalCron, CronExpression: &cronExpr}-- now := time.Date(2024, 1, 15, 10, 0, 0, 0, time.UTC)- lastBackup := time.Date(2024, 1, 14, 2, 0, 0, 0, time.UTC)- result := interval.NextTriggerTime(now, &lastBackup)+// The scheduler acts on ShouldTriggerBackup, so a reported next trigger is only+// truthful when the due check stays false up to it and turns true exactly at it.+func assertNextTriggerMatchesShouldTriggerBackup(+ t *testing.T,+ interval *Interval,+ now time.Time,+ lastBackupTime *time.Time,+ nextTrigger *NextTrigger,+) {+ t.Helper()- assert.NotNil(t, result)- assert.Equal(t, time.Date(2024, 1, 15, 2, 0, 0, 0, time.UTC), *result)- })-- t.Run("Complex cron: 1st and 15th at 4:30", func(t *testing.T) {- cronExpr := "30 4 1,15 * *"- interval := &Interval{Type: IntervalCron, CronExpression: &cronExpr}-- now := time.Date(2024, 1, 10, 10, 0, 0, 0, time.UTC)- lastBackup := time.Date(2024, 1, 1, 4, 30, 0, 0, time.UTC)- result := interval.NextTriggerTime(now, &lastBackup)+ require.Equal(t, interval.ShouldTriggerBackup(now, lastBackupTime), nextTrigger.IsDue)- assert.NotNil(t, result)- assert.Equal(t, time.Date(2024, 1, 15, 4, 30, 0, 0, time.UTC), *result)- })-- t.Run("Invalid cron expression returns nil", func(t *testing.T) {- invalidCron := "invalid cron"- interval := &Interval{Type: IntervalCron, CronExpression: &invalidCron}-- now := time.Date(2024, 1, 15, 10, 0, 0, 0, time.UTC)- lastBackup := time.Date(2024, 1, 14, 10, 0, 0, 0, time.UTC)- result := interval.NextTriggerTime(now, &lastBackup)-- assert.Nil(t, result)- })+ if nextTrigger.IsDue {+ require.Equal(t, now, nextTrigger.ScheduledAt)- t.Run("Empty cron expression returns nil", func(t *testing.T) {- emptyCron := ""- interval := &Interval{Type: IntervalCron, CronExpression: &emptyCron}-- now := time.Date(2024, 1, 15, 10, 0, 0, 0, time.UTC)- lastBackup := time.Date(2024, 1, 14, 10, 0, 0, 0, time.UTC)- result := interval.NextTriggerTime(now, &lastBackup)-- assert.Nil(t, result)- })-- t.Run("Nil cron expression returns nil", func(t *testing.T) {- interval := &Interval{Type: IntervalCron, CronExpression: nil}-- now := time.Date(2024, 1, 15, 10, 0, 0, 0, time.UTC)- lastBackup := time.Date(2024, 1, 14, 10, 0, 0, 0, time.UTC)- result := interval.NextTriggerTime(now, &lastBackup)-- assert.Nil(t, result)- })-}--func TestInterval_NextTriggerTime_UnknownInterval(t *testing.T) {- interval := &Interval{Type: IntervalType("UNKNOWN")}+ return+ }- now := time.Date(2024, 1, 15, 12, 0, 0, 0, time.UTC)- lastBackup := time.Date(2024, 1, 14, 12, 0, 0, 0, time.UTC)- result := interval.NextTriggerTime(now, &lastBackup)+ for moment := now; moment.Before(nextTrigger.ScheduledAt); moment = moment.Add(time.Minute) {+ require.Falsef(t, interval.ShouldTriggerBackup(moment, lastBackupTime),+ "due check fired at %s, before the reported %s", moment, nextTrigger.ScheduledAt)+ }- assert.Nil(t, result)+ require.False(t, interval.ShouldTriggerBackup(nextTrigger.ScheduledAt.Add(-time.Second), lastBackupTime))+ require.True(t, interval.ShouldTriggerBackup(nextTrigger.ScheduledAt, lastBackupTime))}diff --git a/frontend/src/entity/backups/logical/api/logicalBackupsApi.ts b/frontend/src/entity/backups/logical/api/logicalBackupsApi.tsindex 35b25016..9d44e1d8 100644--- a/frontend/src/entity/backups/logical/api/logicalBackupsApi.ts+++ b/frontend/src/entity/backups/logical/api/logicalBackupsApi.ts@@ -2,6 +2,7 @@ import { getApplicationServer } from '../../../../constants';import RequestOptions from '../../../../shared/api/RequestOptions';import { apiHelper } from '../../../../shared/api/apiHelper';import type { GetLogicalBackupsResponse } from '../model/GetLogicalBackupsResponse';+import type { NextScheduledBackupResponse } from '../model/NextScheduledBackupResponse';export interface BackupsFilters {statuses?: string[];@@ -30,6 +31,14 @@ export const logicalBackupsApi = {);},+ async getNextScheduledBackup(databaseId: string) {+ return apiHelper.fetchGetJson<NextScheduledBackupResponse>(+ `${getApplicationServer()}/api/v1/backups/database/${databaseId}/next-backup`,+ undefined,+ true,+ );+ },+async makeBackup(databaseId: string) {const requestOptions: RequestOptions = new RequestOptions();requestOptions.setBody(JSON.stringify({ database_id: databaseId }));diff --git a/frontend/src/entity/backups/logical/index.ts b/frontend/src/entity/backups/logical/index.tsindex 2c4055bd..09827fdc 100644--- a/frontend/src/entity/backups/logical/index.ts+++ b/frontend/src/entity/backups/logical/index.ts@@ -12,3 +12,4 @@ export { LOGICAL_BACKUP_STATUS_LABEL_KEYS } from './model/LogicalBackupStatusLabexport { RESTORE_VERIFICATION_STATUS_LABEL_KEYS } from './model/RestoreVerificationStatusLabelKeys';export { LOGICAL_RETENTION_POLICY_TYPE_LABEL_KEYS } from './model/LogicalRetentionPolicyTypeLabelKeys';export { LOGICAL_BACKUP_NOTIFICATION_TYPE_LABEL_KEYS } from './model/LogicalBackupNotificationTypeLabelKeys';+export type { NextScheduledBackupResponse } from './model/NextScheduledBackupResponse';diff --git a/frontend/src/entity/backups/logical/model/NextScheduledBackupResponse.ts b/frontend/src/entity/backups/logical/model/NextScheduledBackupResponse.tsnew file mode 100644index 00000000..22c1bf4d--- /dev/null+++ b/frontend/src/entity/backups/logical/model/NextScheduledBackupResponse.ts@@ -0,0 +1,6 @@+import type { ScheduledBackupTime } from '../../shared';++export interface NextScheduledBackupResponse {+ // null when no automatic backup will run+ nextBackup: ScheduledBackupTime | null;+}diff --git a/frontend/src/entity/backups/physical/api/physicalBackupsApi.ts b/frontend/src/entity/backups/physical/api/physicalBackupsApi.tsindex 8a4137e4..05541ed0 100644--- a/frontend/src/entity/backups/physical/api/physicalBackupsApi.ts+++ b/frontend/src/entity/backups/physical/api/physicalBackupsApi.ts@@ -2,6 +2,7 @@ import { getApplicationServer } from '../../../../constants';import RequestOptions from '../../../../shared/api/RequestOptions';import { apiHelper } from '../../../../shared/api/apiHelper';import type { GetPhysicalBackupsResponse } from '../model/GetPhysicalBackupsResponse';+import type { NextScheduledBackupsResponse } from '../model/NextScheduledBackupsResponse';import type { PhysicalBackupsFilters } from '../model/PhysicalBackupsFilters';import type { PhysicalRestoreTokenResponse } from '../model/PhysicalRestoreTokenResponse';@@ -31,6 +32,14 @@ export const physicalBackupsApi = {);},+ async getNextScheduledBackups(databaseId: string) {+ return apiHelper.fetchGetJson<NextScheduledBackupsResponse>(+ `${getApplicationServer()}/api/v1/backups/physical/database/${databaseId}/next-backups`,+ undefined,+ true,+ );+ },+async triggerPhysicalBackup(databaseId: string, type: TriggerPhysicalBackupType) {const requestOptions: RequestOptions = new RequestOptions();requestOptions.setBody(JSON.stringify({ type }));diff --git a/frontend/src/entity/backups/physical/index.ts b/frontend/src/entity/backups/physical/index.tsindex 79f3968a..6699d4e4 100644--- a/frontend/src/entity/backups/physical/index.ts+++ b/frontend/src/entity/backups/physical/index.ts@@ -18,3 +18,4 @@ export { PHYSICAL_RETENTION_LABEL_KEYS } from './model/PhysicalRetentionLabelKeyexport { PHYSICAL_BACKUP_TYPE_LABEL_KEYS } from './model/PhysicalBackupTypeLabelKeys';export { PHYSICAL_FULL_BACKUPS_POLICY_LABEL_KEYS } from './model/PhysicalFullBackupsPolicyLabelKeys';export { PHYSICAL_BACKUP_NOTIFICATION_TYPE_LABEL_KEYS } from './model/PhysicalBackupNotificationTypeLabelKeys';+export type { NextScheduledBackupsResponse } from './model/NextScheduledBackupsResponse';diff --git a/frontend/src/entity/backups/physical/model/NextScheduledBackupsResponse.ts b/frontend/src/entity/backups/physical/model/NextScheduledBackupsResponse.tsnew file mode 100644index 00000000..d1a5960e--- /dev/null+++ b/frontend/src/entity/backups/physical/model/NextScheduledBackupsResponse.ts@@ -0,0 +1,7 @@+import type { ScheduledBackupTime } from '../../shared';++export interface NextScheduledBackupsResponse {+ // each is null when no such automatic backup will run+ nextFullBackup: ScheduledBackupTime | null;+ nextIncrementalBackup: ScheduledBackupTime | null;+}diff --git a/frontend/src/entity/backups/shared/index.ts b/frontend/src/entity/backups/shared/index.tsindex dc163900..112044ce 100644--- a/frontend/src/entity/backups/shared/index.ts+++ b/frontend/src/entity/backups/shared/index.ts@@ -2,3 +2,6 @@ export { BackupEncryption } from './model/BackupEncryption';export type { TransferDatabaseRequest } from './model/TransferDatabaseRequest';export { BACKUP_ENCRYPTION_LABEL_KEYS } from './model/BackupEncryptionLabelKeys';export { BACKUP_ENCRYPTION_OPTION_LABEL_KEYS } from './model/BackupEncryptionOptionLabelKeys';+export type { ScheduledBackupTime } from './model/ScheduledBackupTime';+export { isScheduledBackupDue } from './model/isScheduledBackupDue';+export { NextScheduledBackupComponent } from './ui/NextScheduledBackupComponent';diff --git a/frontend/src/entity/backups/shared/model/ScheduledBackupTime.ts b/frontend/src/entity/backups/shared/model/ScheduledBackupTime.tsnew file mode 100644index 00000000..6b935cf7--- /dev/null+++ b/frontend/src/entity/backups/shared/model/ScheduledBackupTime.ts@@ -0,0 +1,6 @@+export interface ScheduledBackupTime {+ scheduledAt: Date;+ // set by the server when the scheduler already treats the backup as due, so a+ // client clock running behind the server cannot postpone it+ isDue: boolean;+}diff --git a/frontend/src/entity/backups/shared/model/isScheduledBackupDue.test.ts b/frontend/src/entity/backups/shared/model/isScheduledBackupDue.test.tsnew file mode 100644index 00000000..44b604f9--- /dev/null+++ b/frontend/src/entity/backups/shared/model/isScheduledBackupDue.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { isScheduledBackupDue } from './isScheduledBackupDue';++const now = new Date('2026-01-15T12:00:00Z');++describe('isScheduledBackupDue', () => {+ it('is due when the server reports it as due, even with a future time', () => {+ expect(+ isScheduledBackupDue({ scheduledAt: new Date('2026-01-15T13:00:00Z'), isDue: true }, now),+ ).toBe(true);+ });++ it('is not due when the scheduled time is still ahead', () => {+ expect(+ isScheduledBackupDue({ scheduledAt: new Date('2026-01-15T12:00:01Z'), isDue: false }, now),+ ).toBe(false);+ });++ it('is due when the scheduled time is exactly now', () => {+ expect(isScheduledBackupDue({ scheduledAt: now, isDue: false }, now)).toBe(true);+ });++ it('is due when the scheduled time has passed', () => {+ expect(+ isScheduledBackupDue({ scheduledAt: new Date('2026-01-15T11:59:59Z'), isDue: false }, now),+ ).toBe(true);+ });++ it('accepts the ISO string the API actually returns', () => {+ const scheduledAt = '2026-01-15T11:00:00Z' as unknown as Date;++ expect(isScheduledBackupDue({ scheduledAt, isDue: false }, now)).toBe(true);+ });+});diff --git a/frontend/src/entity/backups/shared/model/isScheduledBackupDue.ts b/frontend/src/entity/backups/shared/model/isScheduledBackupDue.tsnew file mode 100644index 00000000..368b380b--- /dev/null+++ b/frontend/src/entity/backups/shared/model/isScheduledBackupDue.ts@@ -0,0 +1,8 @@+import dayjs from 'dayjs';++import type { ScheduledBackupTime } from './ScheduledBackupTime';++export const isScheduledBackupDue = (+ scheduledBackupTime: ScheduledBackupTime,+ now: Date = new Date(),+): boolean => scheduledBackupTime.isDue || !dayjs(scheduledBackupTime.scheduledAt).isAfter(now);diff --git a/frontend/src/entity/backups/shared/ui/NextScheduledBackupComponent.tsx b/frontend/src/entity/backups/shared/ui/NextScheduledBackupComponent.tsxnew file mode 100644index 00000000..5d7f37cb--- /dev/null+++ b/frontend/src/entity/backups/shared/ui/NextScheduledBackupComponent.tsx@@ -0,0 +1,44 @@+import dayjs from 'dayjs';+import { useMemo } from 'react';+import { Trans, useTranslation } from 'react-i18next';++import { useLocale } from '../../../../shared/i18n';+import { getUserTimeFormat } from '../../../../shared/time';+import type { ScheduledBackupTime } from '../model/ScheduledBackupTime';+import { isScheduledBackupDue } from '../model/isScheduledBackupDue';++interface Props {+ scheduledBackupTime: ScheduledBackupTime;+ // a literal Tailwind class such as 'min-w-[150px]', aligning the row with the labels above+ labelWidthClassName: string;+}++export const NextScheduledBackupComponent = ({+ scheduledBackupTime,+ labelWidthClassName,+}: Props) => {+ const { t } = useTranslation();+ const { formatRelativeTime } = useLocale();++ const dateTimeFormat = useMemo(() => getUserTimeFormat(), []);++ const nextBackupText = isScheduledBackupDue(scheduledBackupTime) ? (+ t('backups.config.schedule.nextBackupDue')+ ) : (+ <Trans+ i18nKey="backups.config.schedule.nextBackup"+ values={{+ dateTime: dayjs(scheduledBackupTime.scheduledAt).local().format(dateTimeFormat.format),+ relativeTime: formatRelativeTime(scheduledBackupTime.scheduledAt),+ }}+ components={{ lineBreak: <br /> }}+ />+ );++ return (+ <div className="mb-1 flex w-full items-center text-xs text-gray-600 dark:text-gray-400">+ <div className={`${labelWidthClassName} pr-2`} />+ <div>{nextBackupText}</div>+ </div>+ );+};diff --git a/frontend/src/features/backups/logical/ui/ShowLogicalBackupConfigComponent.tsx b/frontend/src/features/backups/logical/ui/ShowLogicalBackupConfigComponent.tsxindex 7bb3e92e..e2e855be 100644--- a/frontend/src/features/backups/logical/ui/ShowLogicalBackupConfigComponent.tsx+++ b/frontend/src/features/backups/logical/ui/ShowLogicalBackupConfigComponent.tsx@@ -1,6 +1,5 @@import { InfoCircleOutlined } from '@ant-design/icons';import { Tooltip } from 'antd';-import { CronExpressionParser } from 'cron-parser';import dayjs from 'dayjs';import { useMemo } from 'react';import { useEffect, useState } from 'react';@@ -11,8 +10,13 @@ import {type LogicalBackupConfig,LogicalRetentionPolicyType,logicalBackupConfigApi,+ logicalBackupsApi,} from '../../../../entity/backups/logical';-import { BACKUP_ENCRYPTION_LABEL_KEYS } from '../../../../entity/backups/shared';+import {+ BACKUP_ENCRYPTION_LABEL_KEYS,+ NextScheduledBackupComponent,+ type ScheduledBackupTime,+} from '../../../../entity/backups/shared';import { type Database, PERIOD_LABEL_KEYS } from '../../../../entity/databases';import {INTERVAL_TYPE_LABEL_KEYS,@@ -21,8 +25,7 @@ import {type Weekday,} from '../../../../entity/intervals';import { getStorageLogoFromType } from '../../../../entity/storages/models/getStorageLogoFromType';-import { type LocalizedText, translateLocalizedText, useLocale } from '../../../../shared/i18n';-import { getUserTimeFormat } from '../../../../shared/time';+import { type LocalizedText, translateLocalizedText } from '../../../../shared/i18n';import {getUserTimeFormat as getIs12Hour,getLocalDayOfMonth,@@ -57,9 +60,9 @@ const getGfsRetentionTexts = (config: LogicalBackupConfig): LocalizedText[] => {export const ShowLogicalBackupConfigComponent = ({ database }: Props) => {const { t } = useTranslation();- const { formatRelativeTime } = useLocale();const listSeparator = t('common.listSeparator');const [backupConfig, setBackupConfig] = useState<LogicalBackupConfig>();+ const [nextBackup, setNextBackup] = useState<ScheduledBackupTime | null>(null);const describeGfsRetention = (config: LogicalBackupConfig): string => {const texts = getGfsRetentionTexts(config);@@ -76,13 +79,14 @@ export const ShowLogicalBackupConfigComponent = ({ database }: Props) => {};}, []);- const dateTimeFormat = useMemo(() => getUserTimeFormat(), []);-useEffect(() => {if (database.id) {logicalBackupConfigApi.getBackupConfigByDbID(database.id).then((res) => {setBackupConfig(res);});+ logicalBackupsApi+ .getNextScheduledBackup(database.id)+ .then((response) => setNextBackup(response.nextBackup));}}, [database]);@@ -148,38 +152,14 @@ export const ShowLogicalBackupConfigComponent = ({ database }: Props) => {)}{backupInterval?.type === IntervalType.CRON && (- <>- <div className="mb-1 flex w-full items-center">- <div className="min-w-[150px] pr-2">- {t('backups.config.schedule.cronExpression')}- </div>- <code className="rounded bg-gray-100 px-2 py-0.5 text-sm dark:bg-gray-700">- {backupInterval?.cronExpression || ''}- </code>+ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[150px] pr-2">+ {t('backups.config.schedule.cronExpression')}</div>- {backupInterval?.cronExpression &&- (() => {- try {- const interval = CronExpressionParser.parse(backupInterval.cronExpression, {- tz: 'UTC',- });- const nextRun = interval.next().toDate();- return (- <div className="mb-1 flex w-full items-center text-xs text-gray-600 dark:text-gray-400">- <div className="min-w-[150px] pr-2" />- <div>- {t('backups.config.schedule.nextRun', {- time: dayjs(nextRun).local().format(dateTimeFormat.format),- })}- <br />({formatRelativeTime(nextRun)})- </div>- </div>- );- } catch {- return null;- }- })()}- </>+ <code className="rounded bg-gray-100 px-2 py-0.5 text-sm dark:bg-gray-700">+ {backupInterval?.cronExpression || ''}+ </code>+ </div>)}{backupInterval?.type !== IntervalType.HOURLY &&@@ -190,6 +170,13 @@ export const ShowLogicalBackupConfigComponent = ({ database }: Props) => {</div>)}+ {nextBackup && (+ <NextScheduledBackupComponent+ scheduledBackupTime={nextBackup}+ labelWidthClassName="min-w-[150px]"+ />+ )}+<div className="mb-1 flex w-full items-center"><div className="min-w-[150px] pr-2">{t('backups.logical.config.retryIfFailedShort')}diff --git a/frontend/src/features/backups/physical/ui/ShowPhysicalBackupConfigComponent.tsx b/frontend/src/features/backups/physical/ui/ShowPhysicalBackupConfigComponent.tsxindex 2b1c8d01..60e972b2 100644--- a/frontend/src/features/backups/physical/ui/ShowPhysicalBackupConfigComponent.tsx+++ b/frontend/src/features/backups/physical/ui/ShowPhysicalBackupConfigComponent.tsx@@ -1,20 +1,25 @@import { InfoCircleOutlined } from '@ant-design/icons';import { Tooltip } from 'antd';-import { CronExpressionParser } from 'cron-parser';import dayjs from 'dayjs';import { type JSX, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import {type FullBackupsRetention,+ type NextScheduledBackupsResponse,PHYSICAL_BACKUP_NOTIFICATION_TYPE_LABEL_KEYS,PHYSICAL_RETENTION_LABEL_KEYS,type PhysicalBackupConfig,PhysicalFullBackupsPolicy,PhysicalRetention,physicalBackupConfigApi,+ physicalBackupsApi,} from '../../../../entity/backups/physical';-import { BACKUP_ENCRYPTION_LABEL_KEYS } from '../../../../entity/backups/shared';+import {+ BACKUP_ENCRYPTION_LABEL_KEYS,+ NextScheduledBackupComponent,+ type ScheduledBackupTime,+} from '../../../../entity/backups/shared';import type { Database } from '../../../../entity/databases';import {INTERVAL_TYPE_LABEL_KEYS,@@ -24,8 +29,7 @@ import {type Weekday,} from '../../../../entity/intervals';import { getStorageLogoFromType } from '../../../../entity/storages';-import { type LocalizedText, translateLocalizedText, useLocale } from '../../../../shared/i18n';-import { getUserTimeFormat } from '../../../../shared/time';+import { type LocalizedText, translateLocalizedText } from '../../../../shared/i18n';import {getUserTimeFormat as getIs12Hour,getLocalDayOfMonth,@@ -60,9 +64,10 @@ const getGfsRetentionTexts = (retention: FullBackupsRetention): LocalizedText[]export const ShowPhysicalBackupConfigComponent = ({ database }: Props): JSX.Element => {const { t } = useTranslation();- const { formatRelativeTime } = useLocale();const listSeparator = t('common.listSeparator');const [backupConfig, setBackupConfig] = useState<PhysicalBackupConfig>();+ const [nextScheduledBackups, setNextScheduledBackups] =+ useState<NextScheduledBackupsResponse | null>(null);const describeGfsRetention = (retention: FullBackupsRetention): string => {const texts = getGfsRetentionTexts(retention);@@ -76,11 +81,12 @@ export const ShowPhysicalBackupConfigComponent = ({ database }: Props): JSX.Elemreturn { use12Hours: is12Hour, format: is12Hour ? 'h:mm A' : 'HH:mm' };}, []);- const dateTimeFormat = useMemo(() => getUserTimeFormat(), []);-- // Read-only mirror of an interval: type, plus local time / weekday / day-of-month- // converted from UTC, or the next cron run.- const renderInterval = (label: string, interval?: Interval): JSX.Element | null => {+ // Time of day, weekday and day of month are stored in UTC and shown in local time.+ const renderInterval = (+ label: string,+ interval: Interval | undefined,+ nextScheduledBackup: ScheduledBackupTime | null | undefined,+ ): JSX.Element | null => {if (!interval?.type) return null;const localTime = interval.timeOfDay@@ -98,27 +104,6 @@ export const ShowPhysicalBackupConfigComponent = ({ database }: Props): JSX.Elem? getLocalDayOfMonth(interval.dayOfMonth, interval.timeOfDay): interval.dayOfMonth;- const renderCronNextRun = (): JSX.Element | null => {- if (!interval.cronExpression) return null;- try {- const parsed = CronExpressionParser.parse(interval.cronExpression, { tz: 'UTC' });- const nextRun = parsed.next().toDate();- return (- <div className="mb-1 flex w-full items-center text-xs text-gray-600 dark:text-gray-400">- <div className="min-w-[180px] pr-2" />- <div>- {t('backups.config.schedule.nextRun', {- time: dayjs(nextRun).local().format(dateTimeFormat.format),- })}- <br />({formatRelativeTime(nextRun)})- </div>- </div>- );- } catch {- return null;- }- };-return (<><div className="mt-4 mb-1 flex w-full items-center">@@ -141,17 +126,12 @@ export const ShowPhysicalBackupConfigComponent = ({ database }: Props): JSX.Elem)}{interval.type === IntervalType.CRON && (- <>- <div className="mb-1 flex w-full items-center">- <div className="min-w-[180px] pr-2">- {t('backups.config.schedule.cronExpression')}- </div>- <code className="rounded bg-gray-100 px-2 py-0.5 text-sm dark:bg-gray-700">- {interval.cronExpression || ''}- </code>- </div>- {renderCronNextRun()}- </>+ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[180px] pr-2">{t('backups.config.schedule.cronExpression')}</div>+ <code className="rounded bg-gray-100 px-2 py-0.5 text-sm dark:bg-gray-700">+ {interval.cronExpression || ''}+ </code>+ </div>)}{interval.type !== IntervalType.HOURLY && interval.type !== IntervalType.CRON && (@@ -160,6 +140,13 @@ export const ShowPhysicalBackupConfigComponent = ({ database }: Props): JSX.Elem<div>{formattedTime}</div></div>)}++ {nextScheduledBackup && (+ <NextScheduledBackupComponent+ scheduledBackupTime={nextScheduledBackup}+ labelWidthClassName="min-w-[180px]"+ />+ )}</>);};@@ -169,6 +156,7 @@ export const ShowPhysicalBackupConfigComponent = ({ database }: Props): JSX.ElemphysicalBackupConfigApi.getPhysicalBackupConfigByDbId(database.id).then((config) => {setBackupConfig(config);});+ physicalBackupsApi.getNextScheduledBackups(database.id).then(setNextScheduledBackups);}}, [database]);@@ -200,10 +188,12 @@ export const ShowPhysicalBackupConfigComponent = ({ database }: Props): JSX.Elem{renderInterval(t('backups.physical.config.fullBackupCadence'),backupConfig.fullBackupInterval,+ nextScheduledBackups?.nextFullBackup,)}{renderInterval(t('backups.physical.config.incrementalBackupCadence'),backupConfig.incrementalBackupInterval,+ nextScheduledBackups?.nextIncrementalBackup,)}<div className="mt-4 mb-1 flex w-full items-center">diff --git a/frontend/src/features/databases/ui/DatabaseCardComponent.tsx b/frontend/src/features/databases/ui/DatabaseCardComponent.tsxindex daf379a2..0ef0026a 100644--- a/frontend/src/features/databases/ui/DatabaseCardComponent.tsx+++ b/frontend/src/features/databases/ui/DatabaseCardComponent.tsx@@ -2,13 +2,19 @@ import { InfoCircleOutlined } from '@ant-design/icons';import { useEffect, useState } from 'react';import { Trans, useTranslation } from 'react-i18next';-import { logicalBackupConfigApi } from '../../../entity/backups/logical';-import { physicalBackupConfigApi } from '../../../entity/backups/physical';+import { logicalBackupConfigApi, logicalBackupsApi } from '../../../entity/backups/logical';+import { physicalBackupConfigApi, physicalBackupsApi } from '../../../entity/backups/physical';+import { type ScheduledBackupTime, isScheduledBackupDue } from '../../../entity/backups/shared';import { type Database, DatabaseType, HEALTH_STATUS_LABEL_KEYS } from '../../../entity/databases';import { HealthStatus } from '../../../entity/databases/model/HealthStatus';import type { Storage } from '../../../entity/storages';import { getStorageLogoFromType } from '../../../entity/storages/models/getStorageLogoFromType';-import { useLocale } from '../../../shared/i18n';+import { type TranslationKey, useLocale } from '../../../shared/i18n';++interface NextBackupLineKeys {+ scheduledKey: TranslationKey;+ dueKey: TranslationKey;+}interface Props {database: Database;@@ -24,6 +30,25 @@ export const DatabaseCardComponent = ({const { t } = useTranslation();const { formatRelativeTime } = useLocale();const [storage, setStorage] = useState<Storage | undefined>();+ const [nextBackup, setNextBackup] = useState<ScheduledBackupTime | null>(null);+ const [nextFullBackup, setNextFullBackup] = useState<ScheduledBackupTime | null>(null);+ const [nextIncrementalBackup, setNextIncrementalBackup] = useState<ScheduledBackupTime | null>(+ null,+ );++ const renderNextBackupLine = (+ scheduledBackupTime: ScheduledBackupTime | null,+ lineKeys: NextBackupLineKeys,+ ) =>+ scheduledBackupTime && (+ <div className="text-gray-500 dark:text-gray-400">+ {isScheduledBackupDue(scheduledBackupTime)+ ? t(lineKeys.dueKey)+ : t(lineKeys.scheduledKey, {+ relativeTime: formatRelativeTime(scheduledBackupTime.scheduledAt),+ })}+ </div>+ );useEffect(() => {if (!database.id) return;@@ -36,6 +61,25 @@ export const DatabaseCardComponent = ({backupConfigRequest.then((config) => setStorage(config?.storage));}, [database.id, database.type]);+ // Keyed on the database object, which the list replaces on every reload, so the+ // next backup refreshes together with the last backup time.+ useEffect(() => {+ if (!database.id) return;++ if (database.type === DatabaseType.POSTGRES_PHYSICAL) {+ physicalBackupsApi.getNextScheduledBackups(database.id).then((response) => {+ setNextFullBackup(response.nextFullBackup);+ setNextIncrementalBackup(response.nextIncrementalBackup);+ });++ return;+ }++ logicalBackupsApi+ .getNextScheduledBackup(database.id)+ .then((response) => setNextBackup(response.nextBackup));+ }, [database]);+return (<divclassName={`mb-3 cursor-pointer rounded p-3 shadow ${selectedDatabaseId === database.id ? 'bg-blue-100 dark:bg-blue-800' : 'bg-white dark:bg-gray-800'}`}@@ -87,6 +131,19 @@ export const DatabaseCardComponent = ({</div>)}+ {renderNextBackupLine(nextBackup, {+ scheduledKey: 'databases.card.nextBackup',+ dueKey: 'databases.card.nextBackupDue',+ })}+ {renderNextBackupLine(nextFullBackup, {+ scheduledKey: 'databases.card.nextFullBackup',+ dueKey: 'databases.card.nextFullBackupDue',+ })}+ {renderNextBackupLine(nextIncrementalBackup, {+ scheduledKey: 'databases.card.nextIncrementalBackup',+ dueKey: 'databases.card.nextIncrementalBackupDue',+ })}+{database.lastBackupErrorMessage && (<div className="mt-1 flex items-center text-sm text-red-600 underline dark:text-red-400"><InfoCircleOutlined className="mr-1" style={{ color: 'red' }} />diff --git a/frontend/src/shared/i18n/locales/en.ts b/frontend/src/shared/i18n/locales/en.tsindex e70d2030..5d0680ff 100644--- a/frontend/src/shared/i18n/locales/en.ts+++ b/frontend/src/shared/i18n/locales/en.ts@@ -303,6 +303,12 @@ export const en = {card: {storage: 'Storage: <storageName/>',lastBackup: 'Last backup {{relativeTime}}',+ nextBackup: 'Next backup {{relativeTime}}',+ nextBackupDue: 'Next backup is about to start',+ nextFullBackup: 'Next full backup {{relativeTime}}',+ nextFullBackupDue: 'Next full backup is about to start',+ nextIncrementalBackup: 'Next incremental backup {{relativeTime}}',+ nextIncrementalBackupDue: 'Next incremental backup is about to start',hasBackupError: 'Has backup error',},tabs: {@@ -1397,6 +1403,8 @@ export const en = {cronExpression: 'Cron expression (UTC)',timeOfDay: 'Time of day',nextRun: 'Next run {{time}}',+ nextBackup: 'Next backup {{dateTime}}<lineBreak/>({{relativeTime}})',+ nextBackupDue: 'Next backup is about to start',invalidCron: 'Invalid cron expression',cronHelp: {format: 'Cron format: minute hour day month weekday (UTC)',diff --git a/frontend/src/shared/i18n/locales/es.ts b/frontend/src/shared/i18n/locales/es.tsindex cd86da28..3da98f71 100644--- a/frontend/src/shared/i18n/locales/es.ts+++ b/frontend/src/shared/i18n/locales/es.ts@@ -310,6 +310,12 @@ export const es: typeof en = {card: {storage: 'Almacenamiento: <storageName/>',lastBackup: 'Última copia de seguridad {{relativeTime}}',+ nextBackup: 'Próxima copia de seguridad {{relativeTime}}',+ nextBackupDue: 'La próxima copia de seguridad está a punto de empezar',+ nextFullBackup: 'Próxima copia completa {{relativeTime}}',+ nextFullBackupDue: 'La próxima copia completa está a punto de empezar',+ nextIncrementalBackup: 'Próxima copia incremental {{relativeTime}}',+ nextIncrementalBackupDue: 'La próxima copia incremental está a punto de empezar',hasBackupError: 'Error en la copia de seguridad',},tabs: {@@ -1425,6 +1431,8 @@ export const es: typeof en = {cronExpression: 'Expresión cron (UTC)',timeOfDay: 'Hora del día',nextRun: 'Próxima ejecución: {{time}}',+ nextBackup: 'Próxima copia de seguridad: {{dateTime}}<lineBreak/>({{relativeTime}})',+ nextBackupDue: 'La próxima copia de seguridad está a punto de empezar',invalidCron: 'Expresión cron no válida',cronHelp: {format: 'Formato cron: minuto, hora, día, mes, día de la semana (UTC)',diff --git a/frontend/src/shared/i18n/locales/fr.ts b/frontend/src/shared/i18n/locales/fr.tsindex 2647461b..31cb28cb 100644--- a/frontend/src/shared/i18n/locales/fr.ts+++ b/frontend/src/shared/i18n/locales/fr.ts@@ -310,6 +310,12 @@ export const fr: typeof en = {card: {storage: 'Stockage : <storageName/>',lastBackup: 'Dernière sauvegarde {{relativeTime}}',+ nextBackup: 'Prochaine sauvegarde {{relativeTime}}',+ nextBackupDue: 'La prochaine sauvegarde va bientôt démarrer',+ nextFullBackup: 'Prochaine sauvegarde complète {{relativeTime}}',+ nextFullBackupDue: 'La prochaine sauvegarde complète va bientôt démarrer',+ nextIncrementalBackup: 'Prochaine sauvegarde incrémentale {{relativeTime}}',+ nextIncrementalBackupDue: 'La prochaine sauvegarde incrémentale va bientôt démarrer',hasBackupError: 'Erreur de sauvegarde',},tabs: {@@ -1434,6 +1440,8 @@ export const fr: typeof en = {cronExpression: 'Expression cron (UTC)',timeOfDay: 'Heure',nextRun: 'Prochaine exécution : {{time}}',+ nextBackup: 'Prochaine sauvegarde : {{dateTime}}<lineBreak/>({{relativeTime}})',+ nextBackupDue: 'La prochaine sauvegarde va bientôt démarrer',invalidCron: 'Expression cron non valide',cronHelp: {format: 'Format cron : minute, heure, jour, mois, jour de la semaine (UTC)',diff --git a/frontend/src/shared/i18n/locales/pt.ts b/frontend/src/shared/i18n/locales/pt.tsindex d174ec53..2501d5ab 100644--- a/frontend/src/shared/i18n/locales/pt.ts+++ b/frontend/src/shared/i18n/locales/pt.ts@@ -309,6 +309,12 @@ export const pt: typeof en = {card: {storage: 'Armazenamento: <storageName/>',lastBackup: 'Último backup {{relativeTime}}',+ nextBackup: 'Próximo backup {{relativeTime}}',+ nextBackupDue: 'O próximo backup está prestes a começar',+ nextFullBackup: 'Próximo backup completo {{relativeTime}}',+ nextFullBackupDue: 'O próximo backup completo está prestes a começar',+ nextIncrementalBackup: 'Próximo backup incremental {{relativeTime}}',+ nextIncrementalBackupDue: 'O próximo backup incremental está prestes a começar',hasBackupError: 'Com erro de backup',},tabs: {@@ -1417,6 +1423,8 @@ export const pt: typeof en = {cronExpression: 'Expressão cron (UTC)',timeOfDay: 'Horário',nextRun: 'Próxima execução: {{time}}',+ nextBackup: 'Próximo backup: {{dateTime}}<lineBreak/>({{relativeTime}})',+ nextBackupDue: 'O próximo backup está prestes a começar',invalidCron: 'Expressão cron inválida',cronHelp: {format: 'Formato cron: minuto hora dia mês dia-da-semana (UTC)',diff --git a/frontend/src/shared/i18n/locales/ru.ts b/frontend/src/shared/i18n/locales/ru.tsindex 85f4cea4..b50833be 100644--- a/frontend/src/shared/i18n/locales/ru.ts+++ b/frontend/src/shared/i18n/locales/ru.ts@@ -304,6 +304,12 @@ export const ru: typeof en = {card: {storage: 'Хранилище: <storageName/>',lastBackup: 'Последний бекап {{relativeTime}}',+ nextBackup: 'Следующий бекап {{relativeTime}}',+ nextBackupDue: 'Следующий бекап вот-вот начнется',+ nextFullBackup: 'Следующий полный бекап {{relativeTime}}',+ nextFullBackupDue: 'Следующий полный бекап вот-вот начнется',+ nextIncrementalBackup: 'Следующий инкрементальный бекап {{relativeTime}}',+ nextIncrementalBackupDue: 'Следующий инкрементальный бекап вот-вот начнется',hasBackupError: 'Есть ошибка бекапа',},tabs: {@@ -1401,6 +1407,8 @@ export const ru: typeof en = {cronExpression: 'Cron-выражение (UTC)',timeOfDay: 'Время',nextRun: 'Следующий запуск: {{time}}',+ nextBackup: 'Следующий бекап: {{dateTime}}<lineBreak/>({{relativeTime}})',+ nextBackupDue: 'Следующий бекап вот-вот начнется',invalidCron: 'Некорректное cron-выражение',cronHelp: {format: 'Формат cron: минута, час, день, месяц, день недели (UTC)',diff --git a/frontend/src/shared/i18n/locales/zh.ts b/frontend/src/shared/i18n/locales/zh.tsindex 0ea6de6a..1e349a90 100644--- a/frontend/src/shared/i18n/locales/zh.ts+++ b/frontend/src/shared/i18n/locales/zh.ts@@ -295,6 +295,12 @@ export const zh: typeof en = {card: {storage: '存储:<storageName/>',lastBackup: '上次备份:{{relativeTime}}',+ nextBackup: '下次备份:{{relativeTime}}',+ nextBackupDue: '下次备份即将开始',+ nextFullBackup: '下次全量备份:{{relativeTime}}',+ nextFullBackupDue: '下次全量备份即将开始',+ nextIncrementalBackup: '下次增量备份:{{relativeTime}}',+ nextIncrementalBackupDue: '下次增量备份即将开始',hasBackupError: '备份出错',},tabs: {@@ -1349,6 +1355,8 @@ export const zh: typeof en = {cronExpression: 'Cron 表达式(UTC)',timeOfDay: '时间',nextRun: '下次运行:{{time}}',+ nextBackup: '下次备份:{{dateTime}}<lineBreak/>({{relativeTime}})',+ nextBackupDue: '下次备份即将开始',invalidCron: '无效的 Cron 表达式',cronHelp: {format: 'Cron 格式:分钟 小时 日 月 星期(UTC)',diff --git a/openspec/changes/archive/2026-10-10-show-next-backup-time/.openspec.yaml b/openspec/changes/archive/2026-10-10-show-next-backup-time/.openspec.yamlnew file mode 100644index 00000000..53f62d70--- /dev/null+++ b/openspec/changes/archive/2026-10-10-show-next-backup-time/.openspec.yaml@@ -0,0 +1,2 @@+schema: spec-driven+created: 2026-10-10diff --git a/openspec/changes/archive/2026-10-10-show-next-backup-time/design.md b/openspec/changes/archive/2026-10-10-show-next-backup-time/design.mdnew file mode 100644index 00000000..5e2b706f--- /dev/null+++ b/openspec/changes/archive/2026-10-10-show-next-backup-time/design.md@@ -0,0 +1,118 @@+## Context++See proposal.md for the motivation. The facts below shape the approach.++- Both schedulers decide whether a backup is due with `Interval.ShouldTriggerBackup(now, lastBackupTime)` in `backend/internal/features/intervals/model.go:72`.+- The logical scheduler calls it on a 15-second tick (`backuping/logical/scheduler.go:19`, `:280`) and passes the newest backup of any status. `FindLastByDatabaseID` in `core/logical/repository.go:122` orders by `created_at` with no status filter. A due backup still does not start when the config has no storage (`StartBackup`, `backuping/logical/scheduler.go:114`).+- The physical scheduler ticks every second (`backuping/physical/constants.go:16`). It skips a config with no storage (`evaluateConfig`, `backuping/physical/scheduler.go:138`). It schedules nothing while a system identifier mismatch is unresolved (`:193`, `hasUnresolvedSystemIdentifierMismatch` at `:523`). It checks the full cadence against the newest full backup of any status (`:178`, `:222`). It checks the incremental cadence only when `isIncrementalEnabled` holds (`:931`), against the newer of that full and the newest incremental (`:205`, `:242`, `newestCreatedAt` at `:847`). When the incremental cadence is due and no chain can be extended, `decideReAnchoringFull` (`:874`) schedules nothing in two cases. One is a chain broken because WAL summarization was off (`:880`). The other is no completed full among the newest attempts (`:894`). In both cases the cadence stays due indefinitely.+- `Interval.NextTriggerTime` already exists (`intervals/model.go:96`), but nothing in production calls it, only `model_test.go:798` onwards. It returns nil when no backup exists. For daily, weekly and monthly schedules it ignores the last backup and returns the next slot after `now` (`nextDailyTrigger` at `:306`, `nextWeeklyTrigger` at `:324`, `nextMonthlyTrigger` at `:358`). After a missed slot it therefore names a future slot while the scheduler fires on its next tick. A nil `TimeOfDay` on a daily interval panics in `nextDailyTrigger` (`:307`), and a malformed one makes it return `now` (`:309`) while the due check returns false (`:164`).+- `ShouldTriggerBackup` catches up a missed slot for daily, hourly and cron schedules. Weekly and monthly schedules compare only against the current week's or month's target (`:187`, `:234`), so a slot missed in an earlier week or month is never caught up.+- A monthly schedule on day 29, 30 or 31 skips every month that lacks that day. `shouldTriggerMonthly` builds the target from the current month with `time.Date` (`:239`). For day 31 in February that target normalizes to March 3, which lies outside February and is never reached while the month is still February. In March the target becomes March 31. `nextMonthlyTrigger` builds the following month with `AddDate(0, 1, 0)` (`:380`) and therefore names the overflow date, such as March 3, that the scheduler never fires on. The reviewer confirmed this by running the current code: day 31, last backup 2026-01-31 03:00, now 2026-01-31 10:00 gives 2026-03-03 03:00, while the due check first fires at 2026-03-31 03:00. Fixing the scheduler is out of scope (see proposal). The display reports the skipped months as they are.+- `BackupConfigService.GetBackupConfigByDbId` inserts a default config when none exists, in both `backups/config/logical/service.go:128` and `backups/config/physical/service.go:173`. Their repositories' `FindByDatabaseID` return nil without writing.+- All schedule times are UTC. The frontend converts them to the browser's timezone with `frontend/src/shared/time/utils.ts`.+- The browser computes "Next run" for cron schedules from the current moment in `ShowLogicalBackupConfigComponent.tsx:163` and in `renderCronNextRun` inside `ShowPhysicalBackupConfigComponent.tsx:103`. The two editors carry their own copies. `DatabaseCardComponent.tsx:28` fetches the backup config for every card in an effect keyed on `[database.id, database.type]`. `DatabasesComponent.tsx:74` reloads the database list every 5 minutes and passes fresh `database` objects to the cards.+- Import direction: `backups/backups/core/logical` imports `backups/config/logical` (`core/logical/interfaces.go`), so the config package cannot import backup history. `backups/backups/services` already imports both backup config packages and both `backuping` packages, and the controllers import `services`.++## Goals / Non-Goals++**Goals:**++- One source of truth for "when is the next backup": the interval rules and the scheduler's own inputs.+- A test that fails if the next-trigger calculation and the due check ever disagree.++**Non-Goals:**++- Changing when any backup runs. `ShouldTriggerBackup` and both schedulers' decisions stay as they are. Extracting an existing condition into a shared helper is allowed only when the tick's behavior does not change.+- Showing next times in lists other than the database card and the read-only settings.++## Decisions++### 1. Compute the time in the backend, not in the browser++The backend computes the next backup time and the frontend only formats it.++Rejected alternative: compute it in the browser from the interval and the card's `lastBackupTime`. The browser lacks the scheduler's input. `lastBackupTime` advances only on success (`backuping/logical/backuper.go:227`), while the scheduler counts failed and in-progress backups too. The browser also cannot see a missing storage, an identity mismatch or a held-back incremental chain. It would also add a fourth copy of the schedule rules in TypeScript.++### 2. Replace `NextTriggerTime` with `GetNextTrigger`, which returns the due state explicitly++`NextTriggerTime` is replaced by `GetNextTrigger(now, lastBackupTime) *NextTrigger`. `NextTrigger` is a small type in the `intervals` package with `ScheduledAt time.Time` (`json:"scheduledAt"`) and `IsDue bool` (`json:"isDue"`). The rename follows the house rule that getters take `Get`.++- `IsDue` is `ShouldTriggerBackup(now, lastBackupTime)`, never inferred from the returned time. When it is true, including the no-backup case, `ScheduledAt` is `now`.+- When nothing is due, `ScheduledAt` is the first slot after `now`. Hourly uses `lastBackupTime + 1h`, and cron uses the schedule's next time after `lastBackupTime`. Daily and weekly reuse `nextDailyTrigger` and `nextWeeklyTrigger`. When nothing is due, the last backup is at or after the latest slot, so the slot after `now` is the right answer for these two.+- The monthly slot is rewritten. It steps month by month from `now`'s month and takes the first month whose `time.Date(year, month, day)` stays inside that month and lies after `now`. Day 31 after January 31 therefore gives March 31, not March 3.+- It returns nil for any interval it cannot evaluate: an unknown type, a missing or malformed `TimeOfDay` on a daily, weekly or monthly interval, a missing weekday or day of month, or a missing or unparsable cron expression. It never panics and never reports a due state the due check would deny.++The contract is the invariant "`ShouldTriggerBackup(t, last)` is false for every minute `t` in `[now, ScheduledAt)` and true at `ScheduledAt`, and `IsDue` equals `ShouldTriggerBackup(now, last)`". A table-driven test in `intervals/model_test.go` walks minute by minute across a window of several months. It covers every interval type, a missing last backup, a missed daily slot, the weekly previous-week case, monthly days 29, 30 and 31 across February and 30-day months, and cron. The invariant is only checked for intervals that pass `Validate`. Invalid intervals get separate cases that expect nil. The existing `TestInterval_NextTriggerTime_*` cases are rewritten to the new function and contract.++Rejected alternatives:++- Keep returning `*time.Time` and derive `isDue` from "returned `now`". A malformed `TimeOfDay` already returns `now` while nothing is due (Context), so the derivation reports false due states.+- Search forward minute by minute with `ShouldTriggerBackup` in production. It is correct by construction, but costs up to tens of thousands of iterations for a monthly schedule on every request.+- Replace both functions with one slot generator that the scheduler also uses. It is the cleaner end state, but it changes scheduler code that decides real backups.++### 3. Put the read-only queries on the schedulers++Each scheduler gets a read-only method that loads exactly the inputs its tick uses and applies `GetNextTrigger`. No method writes.++- Config lookups go through a new `FindBackupConfigByDbId` on each `BackupConfigService`. It wraps the repository's `FindByDatabaseID` and returns nil when no config exists, unlike `GetBackupConfigByDbId`, which inserts a default.+- `BackupsScheduler.GetNextScheduledBackup(databaseID, now) (*intervals.NextTrigger, error)` returns nil when no config exists, backups are disabled or the config has no storage. Otherwise it applies `GetNextTrigger` to the newest backup of any status, loaded through the `FindLastByDatabaseID` call the tick uses.+- `PhysicalBackupsScheduler.GetNextScheduledBackups(databaseID, now) (full, incremental *intervals.NextTrigger, err error)` returns two nils when no config exists, backups are disabled, the config has no storage or an identity mismatch is unresolved. The full time uses the newest full of any status. The incremental time is nil unless `isIncrementalEnabled` holds. It is also nil while the incremental chain is held back: no extendable chain exists, and either `isChainBrokenBySummarizerOff` holds or `hasNoRecentCompletedFull` holds for the newest attempts. Otherwise it comes from `newestCreatedAt`. These conditions do not depend on whether the cadence is due right now, so a held-back chain reports no incremental time in either case.+- The physical method reuses the repository calls and predicates the decision path uses: `FindLastFullAnyStatusByDatabase`, `FindLastByDatabase`, `FindLastExtendableChainByDatabase`, `FindNewestAnyStatusByDatabase` with `recentFullAttemptsWindow`, `hasUnresolvedSystemIdentifierMismatch`, `isChainBrokenBySummarizerOff`, `hasNoRecentCompletedFull` and `newestCreatedAt`. The held-back check may be extracted from `decideReAnchoringFull` into one predicate that both use, but only if the tick's behavior stays the same. Any change to which backup counts as "last", or to when a chain is held back, then lands in one place.++Rejected alternatives:++- Compute it in `backups/backups/services` with its own queries. That works, but it repeats the scheduler's choice of inputs in a second package, which is how the two would drift.+- Add the field to the backup config response. The config package cannot import backup history without an import cycle (see Context).+- Add a field to the `Database` model returned by the database list. It would make the `databases` feature depend on backups, and that model is persisted with GORM.++### 4. Two additive GET endpoints, authorized like the backup lists++- `GET /api/v1/backups/database/:id/next-backup` returns `GetNextScheduledBackupResponse` from `backups/backups/dto/logical`: `{ "nextBackup": { "scheduledAt": "<RFC 3339 UTC>", "isDue": false } }`. `nextBackup` is null when no automatic backup will run.+- `GET /api/v1/backups/physical/database/:id/next-backups` returns `GetNextScheduledBackupsResponse` from `backups/backups/dto/physical`: `{ "nextFullBackup": {...} | null, "nextIncrementalBackup": {...} | null }`.+- Both object fields are `*intervals.NextTrigger`. One type serves both responses and adds no duplicate DTO.+- The service methods are `LogicalBackupService.GetNextScheduledBackup(ctx, user, databaseID)` and `PhysicalBackupService.GetNextScheduledBackups(ctx, user, databaseID)`.++Authorization goes through `DatabaseService.GetDatabase(ctx, user, id)` (`databases/service.go:340`), the same check the physical backup list uses (`services/physical_service.go:80`). It rejects users without access to the database's workspace before any schedule data is read. The controllers sit behind the existing auth middleware, and each endpoint gets swagger annotations.++A request for the wrong database kind is rejected with 400 Bad Request. That covers the logical endpoint for a `POSTGRES_PHYSICAL` database and the physical endpoint for any other type. The kind check runs after the access check, so it reveals nothing to a user without access.++`isDue` comes from the server, so a client clock behind the server cannot turn "due now" into "in a few seconds". The browser still treats a `scheduledAt` that has passed as due when it renders, because the page may stay open past it.++Rejected alternatives:++- One endpoint for both database kinds. The response shapes differ, and the frontend already splits every backup request by kind (`DatabaseCardComponent.tsx:31`).+- Return null for the wrong kind. That hides a caller bug as "no schedule".+- A workspace-wide batch endpoint. It would avoid one request per card, but the card already loads its config per card, and batching is a separate optimization (see proposal, Out of scope).++### 5. Frontend: refresh with the list, one line per schedule++- Types: `ScheduledBackupTime` (`{ scheduledAt: Date; isDue: boolean }`) in its own file under `frontend/src/entity/backups/shared/model`. `NextScheduledBackupResponse` in its own file under `frontend/src/entity/backups/logical/model`. `NextScheduledBackupsResponse` in its own file under `frontend/src/entity/backups/physical/model`. Each is exported through its slice's `index.ts`.+- API methods: `logicalBackupsApi.getNextScheduledBackup(databaseId)` and `physicalBackupsApi.getNextScheduledBackups(databaseId)`.+- `DatabaseCardComponent` loads the next backup in its own effect, keyed on the `database` object. Every 5-minute list reload passes a new object, so the next backup refreshes with the list and with "Last backup". The config effect stays keyed on the id and type, so the config is not refetched. The card renders "Next backup in 3 hours" under "Last backup", or two lines for a physical database: next full and next incremental.+- Due state: a line reads as due now when `isDue` is set or `scheduledAt` is not after the current time. One pure helper, `isScheduledBackupDue`, holds this rule for all three components and is covered by a vitest test. The check runs at render, so a passed time switches to due now at the next refresh, within the same 5 minutes that already apply to "Last backup". No per-card timer is added.+- `ShowLogicalBackupConfigComponent` and `ShowPhysicalBackupConfigComponent` load the next backup when they mount and render a line for every interval type. The two components sit in separate feature slices, which FSD forbids from importing each other, so the line itself is `NextScheduledBackupComponent` in `frontend/src/entity/backups/shared/ui`. The line uses the format of the old "Next run" line: date and time in `dateTimeFormat`, then the relative time. The browser-side cron calculation and its `cron-parser` import are deleted from these two files. The editors keep theirs because they preview an unsaved expression.+- New strings go to all six dictionaries in `frontend/src/shared/i18n/locales`, with English as the source of truth. They cover the card lines for next backup, next full and next incremental, the settings line, and a due-now variant of each. Each is a whole sentence with interpolated values. The English text uses plain hyphens.++Rejected alternatives:++- Reuse the existing `backups.config.schedule.nextRun` key. Its wording says "run", and the editors still use it for the cron preview, so its meaning would split in two.+- Key the card request on `database.lastBackupTime`. That value advances only on success, so a failed backup would leave "due now" on screen until a page reload.+- A per-card timer that re-renders when `scheduledAt` passes. It adds one interval per card to fix staleness that "Last backup" already accepts.++### Module rules this design is constrained by++- `backend/AGENTS.md`: controller tests over unit tests, so the endpoints are covered by `controller_test.go` cases, including denial for a user outside the workspace and for an unauthenticated request. Source-split test files. Swagger annotations on new routes. Getter names start with `Get`.+- `frontend/AGENTS.md`: one type per file in `model/`, no literal user-facing strings, dictionaries typed from `en.ts` so a missing key fails `pnpm build`, whole-sentence keys, plain hyphens in `en.ts`.+- `AGENTS.md`: English in code and identifiers, no issue numbers in production code, no compatibility shims. `NextTriggerTime` and the old browser-side cron line are deleted, not kept alongside their replacements.++## Risks / Trade-offs++- [The displayed incremental time is when the incremental cadence comes due, but the scheduler may take a full backup at that moment when no chain can be extended and the chain is not held back (`decideReAnchoringFull`)] → Accepted and listed as out of scope. A physical backup still happens at the displayed time. Only its kind differs.+- [A failed logical backup with retries enabled is retried on the next tick, while the display names the next scheduled slot] → The gap lasts one tick, 15 seconds at most. After that the retry creates a new backup, and the next refresh recomputes the time.+- [A database with no storage, an identity mismatch or a held-back incremental chain shows no next time, which a user might read as "not scheduled"] → This is accurate: nothing will run until the cause is fixed. Explaining the cause on the card is left out of this change.+- [A monthly schedule on day 29-31 now visibly skips short months] → The display tells the truth about an existing scheduler bug. The fix belongs in a separate change (see proposal).+- [One extra request per database card, repeated every 5 minutes] → Each one is a handful of indexed lookups. Batching can follow if a workspace with many databases shows it.++## Migration Plan++No schema or data migration. The endpoints are additive and the frontend ships in the same release. Rolling back the release removes both together.diff --git a/openspec/changes/archive/2026-10-10-show-next-backup-time/proposal.md b/openspec/changes/archive/2026-10-10-show-next-backup-time/proposal.mdnew file mode 100644index 00000000..2d16e674--- /dev/null+++ b/openspec/changes/archive/2026-10-10-show-next-backup-time/proposal.md@@ -0,0 +1,44 @@+## Why++After setting up a backup schedule, users cannot see when the next automatic backup will run. They have to work it out from the interval or the cron expression, and a timezone or schedule mistake stays hidden until a backup fails to appear. The interface shows a "Next run" line only for cron schedules. That line is computed in the browser from the current moment, so it can disagree with what the scheduler will actually do. The disagreement is largest right after a failed or missed backup, which is exactly when users check the schedule.++## What Changes++- The backend reports the next scheduled backup time for a database and computes it from the same interval rules the scheduler uses to decide whether a backup is due. When a backup is already due, the response says so instead of naming a future slot.+- For a logical database, the backend reports one next backup time.+- For a physical database, the backend reports the next full backup time and, when incremental backups are enabled, the next incremental backup time. WAL streaming is not considered.+- The database card shows "Next backup" under "Last backup".+- The read-only backup settings show a next-backup line for every interval type, both logical and physical. It replaces the cron-only "Next run" line the browser computes there today.+- The interval's next-trigger calculation is replaced and pinned by a test against the scheduler's due check. The current calculation ignores a missed daily, weekly or monthly slot and names the following one, while the scheduler fires on its next tick. For a monthly day the next month lacks, it names an overflow date the scheduler never fires on. Nothing calls it in production today.+- New interface strings are added to all six interface dictionaries.++No existing API, schema or config breaks. The new endpoints are additive. The browser-side cron calculation in the two read-only settings views is deleted, not kept beside the new line.++## Capabilities++### New Capabilities++- `backup-schedule-visibility`: what the user is told about upcoming automatic backups for logical and physical databases, including due, disabled and suppressed states, plus who may read it.++### Modified Capabilities++None. Existing scheduling behavior does not change. This change only reports it.++## Impact++- Backend: `backend/internal/features/intervals` (next-trigger calculation and its tests), the logical and physical backup schedulers (a read-only query that reuses their inputs), `backend/internal/features/backups/backups/services`, the logical and physical backup controllers (two new GET endpoints), swagger docs regenerated with `make swagger`.+- Frontend: backup API clients in `frontend/src/entity/backups`, `DatabaseCardComponent`, `ShowLogicalBackupConfigComponent`, `ShowPhysicalBackupConfigComponent`, and the six dictionaries in `frontend/src/shared/i18n/locales`.+- The database card already loads the backup config for each database. It now makes one more request per card.+- Rules this change answers to: `AGENTS.md`, `backend/AGENTS.md`, `frontend/AGENTS.md`.++## Out of scope++- Changing when backups actually run. That includes the weekly and monthly schedules that skip a missed slot from a previous week or month. It also includes a scheduler bug found while planning: a monthly schedule on day 29, 30 or 31 skips every month without that day, so day 31 runs only seven times a year. The display reports these behaviors as they are. The monthly bug deserves its own change.+- WAL streaming for physical databases.+- Predicting automatic retries after a failed backup, or manual "back up now" requests. The scheduler acts on both within one tick, so the displayed time is stale for seconds at most.+- Telling the user that an incremental slot will produce a full backup because no chain is left to extend. The physical next-incremental time reports the cadence, not the backup kind the scheduler picks at that moment.+- Explaining on the card why no next backup is shown, for example a missing storage, an identity change or a held-back incremental chain.+- Verification schedules, including their cron-only "Next run" line.+- The cron preview in the backup settings editors, which describes an unsaved expression and stays browser-side.+- A batch endpoint for all databases in a workspace.+- A server-configured display timezone. Times are shown in the browser's local timezone, like every other time in the interface.diff --git a/openspec/changes/archive/2026-10-10-show-next-backup-time/specs/backup-schedule-visibility/spec.md b/openspec/changes/archive/2026-10-10-show-next-backup-time/specs/backup-schedule-visibility/spec.mdnew file mode 100644index 00000000..2bf9b8ba--- /dev/null+++ b/openspec/changes/archive/2026-10-10-show-next-backup-time/specs/backup-schedule-visibility/spec.md@@ -0,0 +1,154 @@+## Purpose++Tells users when the next automatic backup of a database will run, so they can confirm a schedule is set up correctly and spot schedule or timezone mistakes without working out the next run themselves.++## ADDED Requirements++### Requirement: The reported next backup time matches when the scheduler will act++For a database with automatic backups enabled, the system SHALL report the earliest moment, at or after the current time, at which the scheduler treats a scheduled backup as due. The calculation SHALL use the same schedule rules and the same last backup the scheduler uses. That last backup is the newest one of any status, including failed and in-progress backups. When a backup is already due, the system SHALL report it as due now instead of naming a future slot.++#### Scenario: Daily schedule before today's slot++- **WHEN** a database has a daily schedule at 03:00 UTC, its last backup ran yesterday at 03:00 UTC, and the current time is 01:00 UTC+- **THEN** the system reports the next backup at 03:00 UTC today++#### Scenario: Daily schedule with a missed slot++- **WHEN** a database has a daily schedule at 03:00 UTC, its last backup ran two days ago, and the current time is 10:00 UTC+- **THEN** the system reports the backup as due now++#### Scenario: Hourly schedule counts a failed backup++- **WHEN** a database has an hourly schedule and its newest backup failed 20 minutes ago+- **THEN** the system reports the next backup one hour after that failed backup started++#### Scenario: Cron schedule++- **WHEN** a database has the cron schedule `0 */6 * * *` and its last backup ran at 06:00 UTC today, and the current time is 08:00 UTC+- **THEN** the system reports the next backup at 12:00 UTC today++#### Scenario: Weekly schedule does not catch up a previous week++- **WHEN** a database has a weekly schedule on Wednesday at 03:00 UTC, its last backup ran three weeks ago, and the current time is Tuesday+- **THEN** the system reports the next backup on Wednesday of the current week at 03:00 UTC++#### Scenario: Monthly schedule on a day the next month lacks++- **WHEN** a database has a monthly schedule on day 31 at 03:00 UTC, its last backup ran on January 31 at 03:00 UTC, and the current time is January 31 at 10:00 UTC+- **THEN** the system reports the next backup on March 31 at 03:00 UTC, because the scheduler skips months without day 31++#### Scenario: No backup exists yet++- **WHEN** a database has automatic backups enabled and no backup exists+- **THEN** the system reports the backup as due now++### Requirement: Physical databases report full and incremental times separately++For a physical database with automatic backups enabled, the system SHALL report the next full backup time from the full backup schedule. When incremental backups are enabled, the system SHALL also report the next incremental backup time from the incremental schedule. The incremental time SHALL be measured from the newest full or incremental backup. When incremental backups are disabled, the system SHALL report no incremental time. WAL streaming SHALL NOT affect either time.++#### Scenario: Full and incremental backups enabled++- **WHEN** a physical database has a weekly full schedule and an hourly incremental schedule+- **THEN** the system reports both the next full backup time and the next incremental backup time++#### Scenario: Full backups only++- **WHEN** a physical database takes full backups only+- **THEN** the system reports the next full backup time and no incremental time++#### Scenario: Incremental backups with WAL streaming++- **WHEN** a physical database takes full and incremental backups and streams WAL+- **THEN** the system reports the next full and the next incremental backup times, computed as if WAL streaming were off++### Requirement: No next backup is reported when automatic backups will not run++The system SHALL report no next backup time when automatic backups are disabled for the database, or when the database has no backup storage. For a physical database, the system SHALL also report no next backup time while automatic backups stay suspended because the database server's identity changed and the change is unresolved. The system SHALL report no next incremental backup time while incremental backups are held back. That happens when no backup chain can be extended and either the chain broke because WAL summarization was off on the server, or none of the newest full backup attempts completed. Reading the next backup time SHALL NOT create or change any backup settings.++#### Scenario: Automatic backups disabled++- **WHEN** automatic backups are disabled for a database+- **THEN** the system reports no next backup time and the interface shows no next-backup line++#### Scenario: No backup storage++- **WHEN** automatic backups are enabled for a database that has no backup storage+- **THEN** the system reports no next backup time++#### Scenario: Database without saved backup settings++- **WHEN** the next backup time is requested for a database whose backup settings were never saved+- **THEN** the system reports no next backup time and creates no backup settings++#### Scenario: Incremental backups held back after WAL summarization was off++- **WHEN** a physical database's incremental chain broke because WAL summarization was off and no chain can be extended+- **THEN** the system reports the next full backup time and no next incremental backup time++#### Scenario: Incremental backups held back after failed full backups++- **WHEN** a physical database has no extendable chain and none of its newest full backup attempts completed+- **THEN** the system reports the next full backup time and no next incremental backup time++#### Scenario: Physical backups suspended after a server identity change++- **WHEN** automatic physical backups are suspended because the database server's identity changed+- **THEN** the system reports no next full and no next incremental backup time++### Requirement: The interface shows the next backup time++The database card SHALL show the next backup time below the last backup time, as a relative time such as "in 3 hours". The read-only backup settings SHALL show the next backup time as a date and time with the relative time beside it, for every schedule type. For a physical database, they SHALL show the next full time under the full schedule and the next incremental time under the incremental schedule. A due backup SHALL read as due now. A reported time that has passed SHALL also read as due now, at the latest when the view next refreshes. The database card SHALL refresh the next backup time whenever it refreshes the last backup time. All times SHALL be displayed in the browser's local timezone, and all new text SHALL be available in every interface language.++#### Scenario: Card for a logical database++- **WHEN** a user views a logical database card whose next backup is in 3 hours+- **THEN** the card shows the last backup line and, under it, a next backup line reading "in 3 hours" in the selected language++#### Scenario: Card for a physical database++- **WHEN** a user views the card of a physical database that takes full and incremental backups+- **THEN** the card shows the next full backup time and the next incremental backup time++#### Scenario: Settings for a daily schedule++- **WHEN** a user opens the read-only backup settings of a database with a daily schedule+- **THEN** the settings show the next backup date and time in the browser's timezone, with the relative time beside it++#### Scenario: Due backup++- **WHEN** the reported next backup is due now or its time has passed+- **THEN** the interface reads it as due now instead of showing a time in the past++### Requirement: A request for the wrong kind of database is rejected++The system SHALL reject a request for a logical database's next backup time when the database is physical, and a request for a physical database's next backup times when the database is logical. The request SHALL fail as invalid instead of reporting that no backup is scheduled.++#### Scenario: Logical request for a physical database++- **WHEN** a user with access asks for the logical next backup time of a physical database+- **THEN** the system rejects the request as invalid++#### Scenario: Physical request for a logical database++- **WHEN** a user with access asks for the physical next backup times of a logical database+- **THEN** the system rejects the request as invalid++### Requirement: Only users who can view a database's backups can read its next backup time++The system SHALL return the next backup time only to a user who is allowed to view that database's backups. Any other request SHALL be rejected and SHALL NOT reveal the schedule, the next backup time, or whether automatic backups are enabled.++#### Scenario: Member of the database's workspace++- **WHEN** a user who can view the database's backups requests its next backup time+- **THEN** the system returns the next backup time++#### Scenario: User outside the database's workspace++- **WHEN** a user without access to the database's workspace requests its next backup time+- **THEN** the system rejects the request and returns no schedule information++#### Scenario: Unauthenticated request++- **WHEN** a request without a valid session asks for a database's next backup time+- **THEN** the system rejects the request as unauthenticateddiff --git a/openspec/changes/archive/2026-10-10-show-next-backup-time/tasks.md b/openspec/changes/archive/2026-10-10-show-next-backup-time/tasks.mdnew file mode 100644index 00000000..f0d8279f--- /dev/null+++ b/openspec/changes/archive/2026-10-10-show-next-backup-time/tasks.md@@ -0,0 +1,40 @@+## 1. Planning review++- [x] 1.1 Pass the planning review gate. The review hooks run it automatically when they are active. When they are disabled, run the reviewer subagent on proposal.md, the backup-schedule-visibility spec, design.md and this task list. Resolve every CHANGES REQUIRED finding before writing code++## 2. Next-trigger calculation++- [x] 2.1 Add the invariant test from design decision 2 to `backend/internal/features/intervals/model_test.go`, written against `GetNextTrigger` and `NextTrigger`. It covers hourly, daily, weekly, monthly and cron schedules, a missing last backup, a missed daily slot, a weekly slot missed in an earlier week, monthly days 29, 30 and 31 across February and 30-day months, and a cron catch-up. Add separate cases that expect nil for invalid intervals: unknown type, missing or malformed time of day, missing weekday or day of month, missing or unparsable cron expression. Verify that the test fails to compile or fails before 2.2, with `go test ./internal/features/intervals/... -count=1`+- [x] 2.2 Replace `Interval.NextTriggerTime` with `GetNextTrigger` and add the `NextTrigger` type. `IsDue` comes from `ShouldTriggerBackup`. When it is due, `ScheduledAt` is `now`, otherwise the per-type slot. Rewrite the monthly slot to skip months without the configured day. Return nil for every interval the slot functions cannot evaluate. Delete `NextTriggerTime` and rewrite the `TestInterval_NextTriggerTime_*` cases for the new function. Verify with `go test ./internal/features/intervals/... -count=1`++## 3. Logical backend++- [x] 3.1 Add `FindBackupConfigByDbId` to the logical `BackupConfigService`. It returns nil when no config exists and never inserts one+- [x] 3.2 Add `GetNextScheduledBackupResponse` to `backend/internal/features/backups/backups/dto/logical`, with `NextBackup *intervals.NextTrigger`+- [x] 3.3 Add `BackupsScheduler.GetNextScheduledBackup(databaseID, now)`. It returns nil when no config exists, backups are disabled or storage is missing. Otherwise it applies `GetNextTrigger` to the newest backup of any status through `FindLastByDatabaseID`. Verify through the controller tests in 3.5+- [x] 3.4 Add `LogicalBackupService.GetNextScheduledBackup(ctx, user, databaseID)`. It authorizes through `DatabaseService.GetDatabase` and then rejects a physical database as a bad request. Add `GET /backups/database/:id/next-backup` with swagger annotations to the logical backups controller+- [x] 3.5 Add controller tests: daily schedule with a future slot, missed slot reported as due, no backups reported as due, disabled backups return a null next backup, missing storage returns a null next backup, a database without saved backup settings returns a null next backup and gains no config row, a physical database is rejected with 400, a user outside the workspace is rejected, and an unauthenticated request is rejected. Verify with `go test ./internal/features/backups/backups/controllers/logical/... -count=1`++## 4. Physical backend++- [x] 4.1 Add `FindBackupConfigByDbId` to the physical `BackupConfigService`. It returns nil when no config exists and never inserts one+- [x] 4.2 Add `GetNextScheduledBackupsResponse` to `backend/internal/features/backups/backups/dto/physical`, with `NextFullBackup` and `NextIncrementalBackup` as `*intervals.NextTrigger`+- [x] 4.3 Add `PhysicalBackupsScheduler.GetNextScheduledBackups(databaseID, now)` as design decision 3 describes. It reports nothing when no config exists, backups are disabled, storage is missing or an identity mismatch is unresolved. The full time comes from the newest full of any status. The incremental time is reported only when incremental backups are enabled and the chain is not held back, and comes from `newestCreatedAt`. If the held-back condition is extracted from `decideReAnchoringFull` into a shared predicate, verify that the tick is unchanged with `go test ./internal/features/backups/backups/backuping/physical/... -count=1`+- [x] 4.4 Add `PhysicalBackupService.GetNextScheduledBackups(ctx, user, databaseID)`. It authorizes through `DatabaseService.GetDatabase` and then rejects a non-physical database as a bad request. Add `GET /backups/physical/database/:id/next-backups` with swagger annotations to the physical backups controller+- [x] 4.5 Add controller tests: full and incremental both reported, full-only configuration reports no incremental, full plus incremental plus WAL stream reports both, disabled backups report neither, missing storage reports neither, an unresolved identity mismatch reports neither, a chain broken by WAL summarization being off reports full only, no completed full among the newest attempts reports full only, a logical database is rejected with 400, a user outside the workspace is rejected, and an unauthenticated request is rejected. Verify with `go test ./internal/features/backups/backups/controllers/physical/... -count=1`+- [x] 4.6 Regenerate swagger with `make swagger` and confirm both new routes appear in the generated docs++## 5. Frontend++- [x] 5.1 Add `ScheduledBackupTime` under `frontend/src/entity/backups/shared/model`, `NextScheduledBackupResponse` under `logical/model` and `NextScheduledBackupsResponse` under `physical/model`, one type per file and exported through each slice's `index.ts`. Add `logicalBackupsApi.getNextScheduledBackup` and `physicalBackupsApi.getNextScheduledBackups`+- [x] 5.2 Add the new strings to `frontend/src/shared/i18n/locales/en.ts` and translate them in `ru.ts`, `es.ts`, `pt.ts`, `zh.ts` and `fr.ts`: card next backup, next full and next incremental lines, the settings line, and a due-now variant of each. Verify that `pnpm build` passes type checking of every dictionary+- [x] 5.3 Add a pure helper `isScheduledBackupDue(scheduledBackupTime, now)` next to `ScheduledBackupTime`, true when `isDue` is set or `scheduledAt` is not after `now`, with a vitest test covering both flags and the boundary. Verify with `pnpm test`+- [x] 5.4 Render the next backup under "Last backup" in `DatabaseCardComponent`. Load it in its own effect keyed on the `database` object, so it refreshes with every list reload. Render one line for logical databases and two for physical ones. Show the due-now text when `isScheduledBackupDue` holds, and no line when the response has none. Verify with `pnpm lint` and `pnpm build`+- [x] 5.5 Replace the browser-side cron "Next run" block in `ShowLogicalBackupConfigComponent` with the API-backed next backup line for every interval type, using `isScheduledBackupDue`, and delete its `cron-parser` usage. Verify with `pnpm lint` and `pnpm build`+- [x] 5.6 Replace `renderCronNextRun` in `ShowPhysicalBackupConfigComponent` with API-backed lines under the full and incremental schedules, using `isScheduledBackupDue`, and delete its `cron-parser` usage. Verify with `pnpm lint` and `pnpm build`++## 6. Verification and review++- [x] 6.1 Run `make lint` in `backend/`, and `pnpm lint`, `pnpm test` and `pnpm build` in `frontend/`. Fix every failure+- [x] 6.2 From `backend/`, rerun the packages this change touches and fix every failure: `go test ./internal/features/intervals/... ./internal/features/backups/config/... ./internal/features/backups/backups/backuping/... ./internal/features/backups/backups/controllers/... -count=1`+- [x] 6.3 Pass the final review gate. The review hooks run it automatically when they are active. When they are disabled, run the reviewer subagent on the working-tree diff. Resolve every CHANGES REQUIRED finding and list refactor suggestions for the diffdiff --git a/openspec/specs/backup-schedule-visibility/spec.md b/openspec/specs/backup-schedule-visibility/spec.mdnew file mode 100644index 00000000..3d417fb6--- /dev/null+++ b/openspec/specs/backup-schedule-visibility/spec.md@@ -0,0 +1,156 @@+# Backup Schedule Visibility Specification++## Purpose++Tells users when the next automatic backup of a database will run, so they can confirm a schedule is set up correctly and spot schedule or timezone mistakes without working out the next run themselves.++## Requirements++### Requirement: The reported next backup time matches when the scheduler will act++For a database with automatic backups enabled, the system SHALL report the earliest moment, at or after the current time, at which the scheduler treats a scheduled backup as due. The calculation SHALL use the same schedule rules and the same last backup the scheduler uses. That last backup is the newest one of any status, including failed and in-progress backups. When a backup is already due, the system SHALL report it as due now instead of naming a future slot.++#### Scenario: Daily schedule before today's slot++- **WHEN** a database has a daily schedule at 03:00 UTC, its last backup ran yesterday at 03:00 UTC, and the current time is 01:00 UTC+- **THEN** the system reports the next backup at 03:00 UTC today++#### Scenario: Daily schedule with a missed slot++- **WHEN** a database has a daily schedule at 03:00 UTC, its last backup ran two days ago, and the current time is 10:00 UTC+- **THEN** the system reports the backup as due now++#### Scenario: Hourly schedule counts a failed backup++- **WHEN** a database has an hourly schedule and its newest backup failed 20 minutes ago+- **THEN** the system reports the next backup one hour after that failed backup started++#### Scenario: Cron schedule++- **WHEN** a database has the cron schedule `0 */6 * * *` and its last backup ran at 06:00 UTC today, and the current time is 08:00 UTC+- **THEN** the system reports the next backup at 12:00 UTC today++#### Scenario: Weekly schedule does not catch up a previous week++- **WHEN** a database has a weekly schedule on Wednesday at 03:00 UTC, its last backup ran three weeks ago, and the current time is Tuesday+- **THEN** the system reports the next backup on Wednesday of the current week at 03:00 UTC++#### Scenario: Monthly schedule on a day the next month lacks++- **WHEN** a database has a monthly schedule on day 31 at 03:00 UTC, its last backup ran on January 31 at 03:00 UTC, and the current time is January 31 at 10:00 UTC+- **THEN** the system reports the next backup on March 31 at 03:00 UTC, because the scheduler skips months without day 31++#### Scenario: No backup exists yet++- **WHEN** a database has automatic backups enabled and no backup exists+- **THEN** the system reports the backup as due now++### Requirement: Physical databases report full and incremental times separately++For a physical database with automatic backups enabled, the system SHALL report the next full backup time from the full backup schedule. When incremental backups are enabled, the system SHALL also report the next incremental backup time from the incremental schedule. The incremental time SHALL be measured from the newest full or incremental backup. When incremental backups are disabled, the system SHALL report no incremental time. WAL streaming SHALL NOT affect either time.++#### Scenario: Full and incremental backups enabled++- **WHEN** a physical database has a weekly full schedule and an hourly incremental schedule+- **THEN** the system reports both the next full backup time and the next incremental backup time++#### Scenario: Full backups only++- **WHEN** a physical database takes full backups only+- **THEN** the system reports the next full backup time and no incremental time++#### Scenario: Incremental backups with WAL streaming++- **WHEN** a physical database takes full and incremental backups and streams WAL+- **THEN** the system reports the next full and the next incremental backup times, computed as if WAL streaming were off++### Requirement: No next backup is reported when automatic backups will not run++The system SHALL report no next backup time when automatic backups are disabled for the database, or when the database has no backup storage. For a physical database, the system SHALL also report no next backup time while automatic backups stay suspended because the database server's identity changed and the change is unresolved. The system SHALL report no next incremental backup time while incremental backups are held back. That happens when no backup chain can be extended and either the chain broke because WAL summarization was off on the server, or none of the newest full backup attempts completed. Reading the next backup time SHALL NOT create or change any backup settings.++#### Scenario: Automatic backups disabled++- **WHEN** automatic backups are disabled for a database+- **THEN** the system reports no next backup time and the interface shows no next-backup line++#### Scenario: No backup storage++- **WHEN** automatic backups are enabled for a database that has no backup storage+- **THEN** the system reports no next backup time++#### Scenario: Database without saved backup settings++- **WHEN** the next backup time is requested for a database whose backup settings were never saved+- **THEN** the system reports no next backup time and creates no backup settings++#### Scenario: Incremental backups held back after WAL summarization was off++- **WHEN** a physical database's incremental chain broke because WAL summarization was off and no chain can be extended+- **THEN** the system reports the next full backup time and no next incremental backup time++#### Scenario: Incremental backups held back after failed full backups++- **WHEN** a physical database has no extendable chain and none of its newest full backup attempts completed+- **THEN** the system reports the next full backup time and no next incremental backup time++#### Scenario: Physical backups suspended after a server identity change++- **WHEN** automatic physical backups are suspended because the database server's identity changed+- **THEN** the system reports no next full and no next incremental backup time++### Requirement: The interface shows the next backup time++The database card SHALL show the next backup time below the last backup time, as a relative time such as "in 3 hours". The read-only backup settings SHALL show the next backup time as a date and time with the relative time beside it, for every schedule type. For a physical database, they SHALL show the next full time under the full schedule and the next incremental time under the incremental schedule. A due backup SHALL read as due now. A reported time that has passed SHALL also read as due now, at the latest when the view next refreshes. The database card SHALL refresh the next backup time whenever it refreshes the last backup time. All times SHALL be displayed in the browser's local timezone, and all new text SHALL be available in every interface language.++#### Scenario: Card for a logical database++- **WHEN** a user views a logical database card whose next backup is in 3 hours+- **THEN** the card shows the last backup line and, under it, a next backup line reading "in 3 hours" in the selected language++#### Scenario: Card for a physical database++- **WHEN** a user views the card of a physical database that takes full and incremental backups+- **THEN** the card shows the next full backup time and the next incremental backup time++#### Scenario: Settings for a daily schedule++- **WHEN** a user opens the read-only backup settings of a database with a daily schedule+- **THEN** the settings show the next backup date and time in the browser's timezone, with the relative time beside it++#### Scenario: Due backup++- **WHEN** the reported next backup is due now or its time has passed+- **THEN** the interface reads it as due now instead of showing a time in the past++### Requirement: A request for the wrong kind of database is rejected++The system SHALL reject a request for a logical database's next backup time when the database is physical, and a request for a physical database's next backup times when the database is logical. The request SHALL fail as invalid instead of reporting that no backup is scheduled.++#### Scenario: Logical request for a physical database++- **WHEN** a user with access asks for the logical next backup time of a physical database+- **THEN** the system rejects the request as invalid++#### Scenario: Physical request for a logical database++- **WHEN** a user with access asks for the physical next backup times of a logical database+- **THEN** the system rejects the request as invalid++### Requirement: Only users who can view a database's backups can read its next backup time++The system SHALL return the next backup time only to a user who is allowed to view that database's backups. Any other request SHALL be rejected and SHALL NOT reveal the schedule, the next backup time, or whether automatic backups are enabled.++#### Scenario: Member of the database's workspace++- **WHEN** a user who can view the database's backups requests its next backup time+- **THEN** the system returns the next backup time++#### Scenario: User outside the database's workspace++- **WHEN** a user without access to the database's workspace requests its next backup time+- **THEN** the system rejects the request and returns no schedule information++#### Scenario: Unauthenticated request++- **WHEN** a request without a valid session asks for a database's next backup time+- **THEN** the system rejects the request as unauthenticated