PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FEATURE (wal): Rebuild the Monitoring tab around what the backups can restore, so a gap a completed incremental bridged no longer turns it red and the screen shows the restorable stretches, a compact layout and values read from the running streamer every second
Rostislav Duginfe19705d9190
diff --git a/backend/internal/features/backups/backups/backuping/physical/testing.go b/backend/internal/features/backups/backups/backuping/physical/testing.goindex 39febbf4..1aa30b89 100644--- a/backend/internal/features/backups/backups/backuping/physical/testing.go+++ b/backend/internal/features/backups/backups/backuping/physical/testing.go@@ -228,3 +228,30 @@ func RunOrphanWalCleanupForTest(t *testing.T, databaseID uuid.UUID) {CreateTestPhysicalCleaner().cleanOrphanWalForDatabase(t.Context(), logger.GetLogger(), databaseID)}++// RegisterTestRunningStreamer makes GetLiveState answer for the database with a+// streamer supervisor that never runs, so a test reads its current values+// without streaming WAL. The registration is removed when the test ends.+func RegisterTestRunningStreamer(+ t *testing.T,+ databaseID uuid.UUID,+ streamer *postgresql_executor.WalStreamSupervisor,+) {+ t.Helper()++ supervisor := GetPhysicalWalStreamSupervisor()++ supervisor.mu.Lock()+ supervisor.running[databaseID] = &runningStreamer{+ cancel: func() {},+ done: make(chan struct{}),+ walStreamSupervisor: streamer,+ }+ supervisor.mu.Unlock()++ t.Cleanup(func() {+ supervisor.mu.Lock()+ delete(supervisor.running, databaseID)+ supervisor.mu.Unlock()+ })+}diff --git a/backend/internal/features/backups/backups/backuping/physical/wal_supervisor.go b/backend/internal/features/backups/backups/backuping/physical/wal_supervisor.goindex 9de19ab1..3f3abf8b 100644--- a/backend/internal/features/backups/backups/backuping/physical/wal_supervisor.go+++ b/backend/internal/features/backups/backups/backuping/physical/wal_supervisor.go@@ -70,6 +70,29 @@ type runningStreamer struct {done chan struct{}watchDir stringshouldRemoveWatchDir atomic.Bool++ // Read by GetLiveState; the HTTP handlers and the streamers share one+ // process, so the running streamer's memory is the live source.+ walStreamSupervisor *postgresql_executor.WalStreamSupervisor+}++// GetLiveState returns the current values of the database's running WAL+// stream, or false while no streamer runs for it in this process.+func (s *PhysicalWalStreamSupervisor) GetLiveState(+ databaseID uuid.UUID,+ now time.Time,+) (*postgresql_executor.WalStreamLiveState, bool) {+ s.mu.Lock()+ streamer, isRunning := s.running[databaseID]+ s.mu.Unlock()++ if !isRunning || streamer.walStreamSupervisor == nil {+ return nil, false+ }++ liveState := streamer.walStreamSupervisor.GetLiveState(now)++ return &liveState, true}func (s *PhysicalWalStreamSupervisor) IsRunning() bool {@@ -287,6 +310,8 @@ func (s *PhysicalWalStreamSupervisor) startStreamer(Logger: s.logger,})+ streamer.walStreamSupervisor = supervisor+s.mu.Lock()s.running[db.ID] = streamers.mu.Unlock()diff --git a/backend/internal/features/backups/backups/controllers/physical/controller.go b/backend/internal/features/backups/backups/controllers/physical/controller.goindex bfd85e46..542d9529 100644--- a/backend/internal/features/backups/backups/controllers/physical/controller.go+++ b/backend/internal/features/backups/backups/controllers/physical/controller.go@@ -28,6 +28,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/wal-stream/statistics", c.GetWalStreamStatistics)+ router.GET("/backups/physical/database/:id/wal-stream/live", c.GetWalStreamLive)router.POST("/backups/physical/database/:id/trigger", c.TriggerBackup)router.POST("/backups/physical/database/:id/restore-token", c.GenerateRestoreToken)@@ -98,9 +99,42 @@ func (c *PhysicalBackupController) GetBackups(ctx *gin.Context) {ctx.JSON(http.StatusOK, response)}+// GetWalStreamLive+// @Summary Get the current WAL stream values of a database+// @Description Returns the current values of a physical PostgreSQL database's running WAL stream, read from the running streamer at the time of the request and never stored, for a screen that refreshes every second: the local queue and its pause size, whether receiving runs, the archive progress point, the time the newest WAL segment was archived and how much is not saved to storage yet. The source-side values (current position, slot status, slot lag, remaining allowance) come from the streamer's newest probe of the source, made at least every 10 seconds, with the time of that probe; the request opens no connection to the source. While no streamer runs for the database, isStreamerRunning is false and current is null. Amounts carry their unit in their name and times are UTC. Any other database type or a database the user cannot view returns 400.+// @Tags backups-physical+// @Produce json+// @Security BearerAuth+// @Param id path string true "Database ID"+// @Success 200 {object} backups_dto_physical.GetWalStreamLiveResponse+// @Failure 400 {object} map[string]string+// @Failure 401 {object} map[string]string+// @Router /backups/physical/database/{id}/wal-stream/live [get]+func (c *PhysicalBackupController) GetWalStreamLive(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.GetWalStreamLive(ctx.Request.Context(), user, databaseID)+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ ctx.JSON(http.StatusOK, response)+}+// GetWalStreamStatistics// @Summary Get WAL stream statistics for a database-// @Description Returns how healthy WAL archiving of a physical PostgreSQL database is: one verdict with its reasons and notices, the streamer's state, the values of the newest sample, a keeping-up summary of the last 10 minutes and a chart series for the requested period. Amounts carry their unit in their name, times are UTC, and the verdict, states, reasons and notices are codes from the documented enums, never display text. Samples are taken every 30 seconds and kept for 7 days. A physical database outside WAL streaming mode gets the NOT_STREAMING verdict with the samples it still has; any other database type, an unknown period or a database the user cannot view returns 400.+// @Description Returns how healthy WAL archiving of a physical PostgreSQL database is: one verdict with its reasons and notices, the latest moment a restore to the latest available point reaches (null before the first completed full backup), the stretches of time the newest chain can restore to (empty before the first completed full backup), the streamer's state, the values of the newest sample, a keeping-up summary of the last 10 minutes and a chart series for the requested period. Amounts carry their unit in their name, times are UTC, and the verdict, states, reasons and notices are codes from the documented enums, never display text. Samples are taken every 30 seconds and kept for 7 days. A physical database outside WAL streaming mode gets the NOT_STREAMING verdict with the samples it still has; any other database type, an unknown period or a database the user cannot view returns 400.// @Tags backups-physical// @Produce json// @Security BearerAuthdiff --git a/backend/internal/features/backups/backups/controllers/physical/controller_test.go b/backend/internal/features/backups/backups/controllers/physical/controller_test.goindex cce3ee98..b77151ed 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,8 @@ import ("encoding/json""io""net/http"+ "os"+ "path/filepath""strconv""strings""testing"@@ -31,6 +33,7 @@ import ("databasus-backend/internal/features/backups/backups/core/physical/wal_health"backups_download "databasus-backend/internal/features/backups/backups/download"backups_dto_physical "databasus-backend/internal/features/backups/backups/dto/physical"+ postgresql_executor "databasus-backend/internal/features/backups/backups/usecases/physical/postgresql"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"@@ -1802,6 +1805,134 @@ func Test_GetWalStreamStatistics_WhenRequestNotAllowed_RefusesWithoutStatistics(}}+func Test_GetWalStreamLive_WhenStreamerRuns_ReturnsValuesReadAtRequestTime(t *testing.T) {+ prereqs := createWalStreamingControllerPrereqs(t)+ newestSegment := seedTestWalSegmentReceivedAt(t, prereqs, 0x10, time.Now().UTC().Add(-time.Minute))++ watchDir := registerTestRunningWalStreamer(t, prereqs)+ require.NoError(t, os.MkdirAll(watchDir, 0o700))+ writeTestWalFile(t, watchDir, walmath.WalSegmentNo(0x11).GetFilename(1), 3*1024*1024)++ firstReading := getWalStreamLive(t, prereqs)++ require.True(t, firstReading.IsStreamerRunning)+ require.NotNil(t, firstReading.Current)+ assert.WithinDuration(t, time.Now().UTC(), firstReading.Current.MeasuredAt, 5*time.Second)+ assert.Equal(t, int64(3*1024*1024), firstReading.Current.LocalQueueBytes)+ require.NotNil(t, firstReading.Current.LastArchivedWalAt)+ assert.WithinDuration(t, newestSegment.ReceivedAt, *firstReading.Current.LastArchivedWalAt, time.Millisecond)+ assert.Nil(t, firstReading.Current.SourceProbedAt, "no probe of the source has run yet")+ assert.Nil(t, firstReading.Current.SlotLagBytes)++ require.NoError(t, os.Remove(filepath.Join(watchDir, walmath.WalSegmentNo(0x11).GetFilename(1))))++ secondReading := getWalStreamLive(t, prereqs)++ assert.Equal(t, int64(0), secondReading.Current.LocalQueueBytes,+ "the next reading sees the drained buffer without waiting for a sample")+}++func Test_GetWalStreamLive_WhenNoStreamerRuns_SaysSoWithoutValues(t *testing.T) {+ prereqs := createWalStreamingControllerPrereqs(t)++ response := test_utils.MakeGetRequest(t, prereqs.router, getWalStreamLiveURL(prereqs.database.ID),+ "Bearer "+prereqs.user.Token, http.StatusOK)++ assert.JSONEq(t, `{"isStreamerRunning":false,"current":null}`, string(response.Body))+}++func Test_GetWalStreamLive_WhenRequestNotAllowed_RefusesWithoutValues(t *testing.T) {+ prereqs := createWalStreamingControllerPrereqs(t)+ registerTestRunningWalStreamer(t, prereqs)++ outsider := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)++ logicalDatabase := databases.CreateTestDatabase(prereqs.workspace.ID, prereqs.storage, prereqs.notifier)+ t.Cleanup(func() { databases.RemoveTestDatabase(context.Background(), logicalDatabase) })++ testCases := []struct {+ name string+ url string+ authToken string+ expectedStatus int+ }{+ {+ name: "User from another workspace",+ url: getWalStreamLiveURL(prereqs.database.ID),+ authToken: "Bearer " + outsider.Token,+ expectedStatus: http.StatusBadRequest,+ },+ {+ name: "Unauthenticated request",+ url: getWalStreamLiveURL(prereqs.database.ID),+ authToken: "",+ expectedStatus: http.StatusUnauthorized,+ },+ {+ name: "Logical database",+ url: getWalStreamLiveURL(logicalDatabase.ID),+ authToken: "Bearer " + prereqs.user.Token,+ expectedStatus: http.StatusBadRequest,+ },+ }++ for _, testCase := range testCases {+ t.Run(testCase.name, func(t *testing.T) {+ response := test_utils.MakeGetRequest(t, prereqs.router, testCase.url, testCase.authToken,+ testCase.expectedStatus)++ assert.NotContains(t, string(response.Body), `"localQueueBytes"`)+ })+ }+}++// The streamer is built but never run: its current values come from the watch+// directory and the catalog, which the test controls. Returns the watch+// directory.+func registerTestRunningWalStreamer(t *testing.T, prereqs *physicalControllerPrereqs) string {+ t.Helper()++ watchDirRoot := t.TempDir()++ streamer := postgresql_executor.NewWalStreamSupervisor(postgresql_executor.WalStreamSpec{+ DatabaseID: prereqs.database.ID,+ SourceDB: prereqs.database.PostgresqlPhysical,+ WalSegmentRepo: physical_repositories.GetWalSegmentRepository(),+ WatchDirRoot: watchDirRoot,+ Logger: logger.GetLogger(),+ })+ backuping_physical.RegisterTestRunningStreamer(t, prereqs.database.ID, streamer)++ return filepath.Join(watchDirRoot, "wal-queue", prereqs.database.ID.String())+}++func writeTestWalFile(t *testing.T, dir, name string, sizeBytes int64) {+ t.Helper()++ file, err := os.Create(filepath.Join(dir, name))+ require.NoError(t, err)+ require.NoError(t, file.Truncate(sizeBytes))+ require.NoError(t, file.Close())+}++func getWalStreamLive(+ t *testing.T,+ prereqs *physicalControllerPrereqs,+) *backups_dto_physical.GetWalStreamLiveResponse {+ t.Helper()++ var response backups_dto_physical.GetWalStreamLiveResponse++ test_utils.MakeGetRequestAndUnmarshal(t, prereqs.router, getWalStreamLiveURL(prereqs.database.ID),+ "Bearer "+prereqs.user.Token, http.StatusOK, &response)++ return &response+}++func getWalStreamLiveURL(databaseID uuid.UUID) string {+ return "/api/v1/backups/physical/database/" + databaseID.String() + "/wal-stream/live"+}+func Test_GetWalStreamStatistics_ForWeek_ReturnsAtMost360PointsWithArchiveRatePerCoveredSecond(t *testing.T) {prereqs := createWalStreamingControllerPrereqs(t)createHealthyTestWalStreamer(t, prereqs.database.ID)@@ -1944,6 +2075,8 @@ func Test_GetWalStreamStatistics_WhenNeedsAttention_ReturnsOnlyDocumentedCodes(tsample.LocalQueueBytes = sample.LocalQueuePauseBytessample.SlotSafeWalSizeBytes = nil})+ seedTestCompletedFullAtSegment(t, prereqs, 0x10, time.Now().UTC().Add(-time.Hour))+ seedTestWalSegmentReceivedAt(t, prereqs, 0x10, time.Now().UTC().Add(-30*time.Minute))response := test_utils.MakeGetRequest(t, prereqs.router, getWalStreamStatisticsURL(prereqs.database.ID, "DAY"),"Bearer "+prereqs.user.Token, http.StatusOK)@@ -1955,6 +2088,7 @@ func Test_GetWalStreamStatistics_WhenNeedsAttention_ReturnsOnlyDocumentedCodes(tassert.Equal(t, []wal_health.ReasonCode{wal_health.ReasonCodeLocalQueueFilling},getReasonCodes(statistics.Health.Reasons))assert.Contains(t, getNoticeCodes(statistics.Health.Notices), wal_health.NoticeCodeNoSlotWalLimit)+ require.NotEmpty(t, statistics.RestorableRanges, "the format check also covers the restorable ranges")var body anyrequire.NoError(t, json.Unmarshal(response.Body, &body))@@ -2116,6 +2250,213 @@ func Test_GetWalStreamStatistics_WhenIncrementalBrokeChainWithGap_StillReportsWa"a chain broken by an incremental still has a completed full backup")}+func Test_GetWalStreamStatistics_WhenWalFollowsFullWithoutGap_ReportsNewestSegmentAsLatestRestorable(t *testing.T) {+ prereqs := createWalStreamingControllerPrereqs(t)+ now := time.Now().UTC()++ seedTestCompletedFullAtSegment(t, prereqs, 0x10, now.Add(-time.Hour))+ seedTestWalSegmentReceivedAt(t, prereqs, 0x10, now.Add(-30*time.Minute))+ newestSegment := seedTestWalSegmentReceivedAt(t, prereqs, 0x11, now.Add(-time.Minute))++ response := getWalStreamStatistics(t, prereqs, "HOUR")++ require.NotNil(t, response.LatestRestorableAt)+ assert.WithinDuration(t, newestSegment.ReceivedAt, *response.LatestRestorableAt, time.Millisecond)+ assert.Equal(t, time.UTC, response.LatestRestorableAt.Location())+}++func Test_GetWalStreamStatistics_WhenNewestChainHasGap_ReportsSegmentBeforeGapAsLatestRestorable(t *testing.T) {+ prereqs := createWalStreamingControllerPrereqs(t)+ now := time.Now().UTC()++ seedTestCompletedFullAtSegment(t, prereqs, 0x10, now.Add(-time.Hour))+ seedTestWalSegmentReceivedAt(t, prereqs, 0x10, now.Add(-30*time.Minute))+ segmentBeforeGap := seedTestWalSegmentReceivedAt(t, prereqs, 0x11, now.Add(-20*time.Minute))+ seedTestWalSegmentReceivedAt(t, prereqs, 0x13, now.Add(-10*time.Minute))+ seedTestWalSegmentReceivedAt(t, prereqs, 0x14, now.Add(-time.Minute))++ response := getWalStreamStatistics(t, prereqs, "HOUR")++ require.NotNil(t, response.LatestRestorableAt)+ assert.WithinDuration(t, segmentBeforeGap.ReceivedAt, *response.LatestRestorableAt, time.Millisecond)+}++func Test_GetWalStreamStatistics_WhenIncrementalCompletedAfterGap_ReportsNewestSegmentAsLatestRestorable(t *testing.T) {+ prereqs := createWalStreamingControllerPrereqs(t)+ now := time.Now().UTC()++ full := seedTestCompletedFullAtSegment(t, prereqs, 0x10, now.Add(-time.Hour))+ seedTestWalSegmentReceivedAt(t, prereqs, 0x10, now.Add(-50*time.Minute))+ seedTestWalSegmentReceivedAt(t, prereqs, 0x11, now.Add(-40*time.Minute))++ incrementalStartLSN := walmath.LSN(0x13*segmentBytes + physical_testing.FirstRecordOffset)+ incrementalAfterGap := physical_testing.NewTestCompletedIncrementalBackup(prereqs.database.ID, prereqs.storage.ID,+ full.ID, nil, 1, incrementalStartLSN, incrementalStartLSN+physical_testing.FullLSNSpan)+ incrementalAfterGap.CompletedAt = new(now.Add(-20 * time.Minute))+ physical_testing.CreateTestIncrementalBackup(t, incrementalAfterGap)++ seedTestWalSegmentReceivedAt(t, prereqs, 0x13, now.Add(-15*time.Minute))+ newestSegment := seedTestWalSegmentReceivedAt(t, prereqs, 0x14, now.Add(-time.Minute))++ response := getWalStreamStatistics(t, prereqs, "HOUR")++ require.NotNil(t, response.LatestRestorableAt)+ assert.WithinDuration(t, newestSegment.ReceivedAt, *response.LatestRestorableAt, time.Millisecond,+ "a gap below the newest completed backup does not limit the latest restore")+}++func Test_GetWalStreamStatistics_WhenIncrementalBridgesGap_ReportsHealthyWithTwoRestorableRanges(t *testing.T) {+ prereqs := createWalStreamingControllerPrereqs(t)+ createHealthyTestWalStreamer(t, prereqs.database.ID)+ now := time.Now().UTC()+ seedTestWalStreamSamples(t, prereqs.database.ID, 4, now, nil)++ full := seedTestCompletedFullAtSegment(t, prereqs, 0x10, now.Add(-time.Hour))+ seedTestWalSegmentReceivedAt(t, prereqs, 0x10, now.Add(-50*time.Minute))+ segmentBeforeGap := seedTestWalSegmentReceivedAt(t, prereqs, 0x11, now.Add(-40*time.Minute))+ incrementalAfterGap := seedTestCompletedIncrementalAtSegment(t, prereqs, full, 0x13, now.Add(-20*time.Minute))+ seedTestWalSegmentReceivedAt(t, prereqs, 0x13, now.Add(-15*time.Minute))+ newestSegment := seedTestWalSegmentReceivedAt(t, prereqs, 0x14, now.Add(-time.Minute))++ response := getWalStreamStatistics(t, prereqs, "HOUR")++ assert.Equal(t, wal_health.HealthLevelHealthy, response.Health.Level)+ assert.NotContains(t, getReasonCodes(response.Health.Reasons), wal_health.ReasonCodeWalChainBroken,+ "a gap the latest restore crosses through a completed incremental does not break the chain")++ require.NotNil(t, response.LatestRestorableAt)+ assert.WithinDuration(t, newestSegment.ReceivedAt, *response.LatestRestorableAt, time.Millisecond)++ require.Len(t, response.RestorableRanges, 2, "the moments inside the gap cannot be restored")+ assert.WithinDuration(t, *full.CompletedAt, response.RestorableRanges[0].From, time.Millisecond)+ assert.WithinDuration(t, segmentBeforeGap.ReceivedAt, response.RestorableRanges[0].To, time.Millisecond)+ assert.WithinDuration(t, *incrementalAfterGap.CompletedAt, response.RestorableRanges[1].From, time.Millisecond)+ assert.WithinDuration(t, newestSegment.ReceivedAt, response.RestorableRanges[1].To, time.Millisecond)+ assert.Equal(t, time.UTC, response.RestorableRanges[0].From.Location())+}++func Test_GetWalStreamStatistics_WhenGapFollowsNewestIncremental_ReportsWalChainBroken(t *testing.T) {+ prereqs := createWalStreamingControllerPrereqs(t)+ createHealthyTestWalStreamer(t, prereqs.database.ID)+ now := time.Now().UTC()+ seedTestWalStreamSamples(t, prereqs.database.ID, 4, now, nil)++ full := seedTestCompletedFullAtSegment(t, prereqs, 0x10, now.Add(-time.Hour))+ seedTestWalSegmentReceivedAt(t, prereqs, 0x10, now.Add(-50*time.Minute))+ seedTestCompletedIncrementalAtSegment(t, prereqs, full, 0x11, now.Add(-45*time.Minute))+ segmentBeforeGap := seedTestWalSegmentReceivedAt(t, prereqs, 0x11, now.Add(-40*time.Minute))+ seedTestWalSegmentReceivedAt(t, prereqs, 0x13, now.Add(-time.Minute))++ response := getWalStreamStatistics(t, prereqs, "HOUR")++ assert.Equal(t, wal_health.HealthLevelBroken, response.Health.Level)+ assert.Equal(t, []wal_health.ReasonCode{wal_health.ReasonCodeWalChainBroken},+ getReasonCodes(response.Health.Reasons))++ require.NotNil(t, response.LatestRestorableAt)+ assert.WithinDuration(t, segmentBeforeGap.ReceivedAt, *response.LatestRestorableAt, time.Millisecond)+ require.Len(t, response.RestorableRanges, 1)+ assert.WithinDuration(t, segmentBeforeGap.ReceivedAt, response.RestorableRanges[0].To, time.Millisecond)+}++func Test_GetWalStreamStatistics_WhenIncrementalAfterGapFailed_ReportsWalChainBroken(t *testing.T) {+ prereqs := createWalStreamingControllerPrereqs(t)+ createHealthyTestWalStreamer(t, prereqs.database.ID)+ now := time.Now().UTC()+ seedTestWalStreamSamples(t, prereqs.database.ID, 4, now, nil)++ full := seedCompletedFullWithWalGap(t, prereqs)++ incrementalStartLSN := walmath.LSN(0x13*segmentBytes + physical_testing.FirstRecordOffset)+ failedIncremental := physical_testing.NewTestCompletedIncrementalBackup(prereqs.database.ID, prereqs.storage.ID,+ full.ID, nil, 1, incrementalStartLSN, incrementalStartLSN+physical_testing.FullLSNSpan)+ failedIncremental.Status = physical_enums.PhysicalBackupStatusError+ physical_testing.CreateTestIncrementalBackup(t, failedIncremental)++ response := getWalStreamStatistics(t, prereqs, "HOUR")++ assert.Equal(t, wal_health.HealthLevelBroken, response.Health.Level)+ assert.Contains(t, getReasonCodes(response.Health.Reasons), wal_health.ReasonCodeWalChainBroken,+ "a failed incremental does not bridge the gap")+ assert.Len(t, response.RestorableRanges, 1)+}++func Test_GetWalStreamStatistics_WhenFullHasNoWalAfterIt_ReportsFullCompletionAsLatestRestorable(t *testing.T) {+ prereqs := createWalStreamingControllerPrereqs(t)++ full := seedTestCompletedFullAtSegment(t, prereqs, 0x10, time.Now().UTC().Add(-time.Hour))++ response := getWalStreamStatistics(t, prereqs, "HOUR")++ require.NotNil(t, response.LatestRestorableAt)+ assert.WithinDuration(t, *full.CompletedAt, *response.LatestRestorableAt, time.Millisecond)+}++func Test_GetWalStreamStatistics_WhenNoFullBackupCompleted_ReportsNoLatestRestorable(t *testing.T) {+ prereqs := createWalStreamingControllerPrereqs(t)+ seedTestWalSegmentReceivedAt(t, prereqs, 0x10, time.Now().UTC())++ response := test_utils.MakeGetRequest(t, prereqs.router, getWalStreamStatisticsURL(prereqs.database.ID, "HOUR"),+ "Bearer "+prereqs.user.Token, http.StatusOK)++ var statistics backups_dto_physical.GetWalStreamStatisticsResponse+ require.NoError(t, json.Unmarshal(response.Body, &statistics))++ assert.Nil(t, statistics.LatestRestorableAt)+ assert.Contains(t, string(response.Body), `"restorableRanges":[]`, "the list is empty, not null")+}++func seedTestCompletedFullAtSegment(+ t *testing.T,+ prereqs *physicalControllerPrereqs,+ segmentNo uint64,+ completedAt time.Time,+) *physical_models.PhysicalFullBackup {+ t.Helper()++ startLSN := walmath.LSN(segmentNo*segmentBytes + physical_testing.FirstRecordOffset)+ full := physical_testing.NewTestCompletedFullBackup(prereqs.database.ID, prereqs.storage.ID, 1,+ startLSN, startLSN+physical_testing.FullLSNSpan)+ full.CompletedAt = &completedAt++ return physical_testing.CreateTestFullBackup(t, full)+}++// The incremental starts and stops inside segmentNo, so the WAL from that+// segment on continues it.+func seedTestCompletedIncrementalAtSegment(+ t *testing.T,+ prereqs *physicalControllerPrereqs,+ full *physical_models.PhysicalFullBackup,+ segmentNo uint64,+ completedAt time.Time,+) *physical_models.PhysicalIncrementalBackup {+ t.Helper()++ startLSN := walmath.LSN(segmentNo*segmentBytes + physical_testing.FirstRecordOffset)+ incremental := physical_testing.NewTestCompletedIncrementalBackup(prereqs.database.ID, prereqs.storage.ID,+ full.ID, nil, 1, startLSN, startLSN+physical_testing.FullLSNSpan)+ incremental.CompletedAt = &completedAt++ return physical_testing.CreateTestIncrementalBackup(t, incremental)+}++func seedTestWalSegmentReceivedAt(+ t *testing.T,+ prereqs *physicalControllerPrereqs,+ segmentNo uint64,+ receivedAt time.Time,+) *physical_models.PhysicalWalSegment {+ t.Helper()++ segment := physical_testing.NewTestWalSegment(prereqs.database.ID, prereqs.storage.ID, 1,+ walmath.WalSegmentNo(segmentNo).GetFilename(1),+ walmath.LSN(segmentNo*segmentBytes), walmath.LSN((segmentNo+1)*segmentBytes))+ segment.ReceivedAt = receivedAt++ return physical_testing.CreateTestWalSegment(t, segment)+}+func Test_GetWalStreamStatistics_ForFullBackupRequestOrRun_ReportsFullBackupPending(t *testing.T) {prereqs := createWalStreamingControllerPrereqs(t)diff --git a/backend/internal/features/backups/backups/core/physical/chain_view/restore_coverage.go b/backend/internal/features/backups/backups/core/physical/chain_view/restore_coverage.gonew file mode 100644index 00000000..77af8eda--- /dev/null+++ b/backend/internal/features/backups/backups/core/physical/chain_view/restore_coverage.go@@ -0,0 +1,164 @@+package chain_view++import (+ "errors"+ "slices"+ "sort"+ "time"++ "github.com/google/uuid"++ physical_models "databasus-backend/internal/features/backups/backups/core/physical/models"+ "databasus-backend/internal/util/walmath"+)++type TimeRange struct {+ From time.Time+ To time.Time+}++// RestoreCoverage says what the newest chain can restore right now. It is+// empty while no full backup has completed.+type RestoreCoverage struct {+ // LatestRestorableAt is the moment a restore to the latest available point+ // reaches.+ LatestRestorableAt *time.Time++ // RestorableRanges are the stretches of time a restore can target, oldest+ // first. The last one ends at LatestRestorableAt.+ RestorableRanges []TimeRange++ // BlockingGaps are the WAL gaps above the newest completed backup of the+ // chain, which the latest restore cannot cross. A gap below that backup is+ // bridged by it.+ BlockingGaps []LSNRange+}++type restoreAnchor struct {+ stopLSN walmath.LSN+ completedAt time.Time+}++// GetRestoreCoverage shares the resolution of ResolveRestoreSet, so a screen+// showing it never promises more than the restore delivers.+func (s *ChainViewService) GetRestoreCoverage(databaseID uuid.UUID) (*RestoreCoverage, error) {+ reach, err := s.resolveRestoreReach(databaseID, nil)+ if errors.Is(err, ErrNoChainForRestore) {+ return &RestoreCoverage{RestorableRanges: []TimeRange{}}, nil+ }++ if err != nil {+ return nil, err+ }++ blockingGaps := make([]LSNRange, 0)++ for _, gap := range findGapsBetweenSegments(reach.walSegments) {+ if gap.End > reach.lastStopLSN {+ blockingGaps = append(blockingGaps, gap)+ }+ }++ return &RestoreCoverage{+ LatestRestorableAt: &reach.reachableTime,+ RestorableRanges: findRestorableRanges(getRestoreAnchors(reach), reach.walSegments),+ BlockingGaps: blockingGaps,+ }, nil+}++// getRestoreAnchors lists the backups a restore can start from: the full+// backup and the incrementals a latest restore includes.+func getRestoreAnchors(reach *restoreReach) []restoreAnchor {+ anchors := make([]restoreAnchor, 0, len(reach.incrementals)+1)+ anchors = append(anchors, restoreAnchor{+ stopLSN: *reach.chain.RootFull.StopLSN,+ completedAt: derefTime(reach.chain.RootFull.CompletedAt),+ })++ for _, incremental := range reach.incrementals {+ anchors = append(anchors, restoreAnchor{+ stopLSN: *incremental.StopLSN,+ completedAt: *incremental.CompletedAt,+ })+ }++ return anchors+}++// findRestorableRanges opens a range at each anchor's completion and ends it+// where contiguousWalRun from that anchor would stop. The run ends are found+// once for all anchors, so the cost does not grow with anchors × segments.+func findRestorableRanges(+ anchors []restoreAnchor,+ segments []*physical_models.PhysicalWalSegment,+) []TimeRange {+ committedSegments := make([]*physical_models.PhysicalWalSegment, 0, len(segments))++ for _, segment := range segments {+ if segment.FileName != nil {+ committedSegments = append(committedSegments, segment)+ }+ }++ runEnds := findContiguousRunEnds(committedSegments)+ ranges := make([]TimeRange, 0, len(anchors))++ for _, anchor := range anchors {+ reachedAt := anchor.completedAt++ firstAfterAnchor := sort.Search(len(committedSegments), func(index int) bool {+ return committedSegments[index].EndLSN > anchor.stopLSN+ })++ if firstAfterAnchor < len(committedSegments) &&+ committedSegments[firstAfterAnchor].StartLSN <= anchor.stopLSN {+ reachedAt = committedSegments[runEnds[firstAfterAnchor]].ReceivedAt+ }++ if reachedAt.Before(anchor.completedAt) {+ reachedAt = anchor.completedAt+ }++ ranges = append(ranges, TimeRange{From: anchor.completedAt, To: reachedAt})+ }++ return mergeTimeRanges(ranges)+}++// findContiguousRunEnds maps each segment to the last segment of the unbroken+// run it starts, by the continuity rule of contiguousWalRun.+func findContiguousRunEnds(segments []*physical_models.PhysicalWalSegment) []int {+ runEnds := make([]int, len(segments))++ for index := len(segments) - 1; index >= 0; index-- {+ runEnds[index] = index++ if index+1 < len(segments) && segments[index+1].StartLSN <= segments[index].EndLSN {+ runEnds[index] = runEnds[index+1]+ }+ }++ return runEnds+}++func mergeTimeRanges(ranges []TimeRange) []TimeRange {+ slices.SortFunc(ranges, func(a, b TimeRange) int { return a.From.Compare(b.From) })++ merged := make([]TimeRange, 0, len(ranges))++ for _, timeRange := range ranges {+ last := len(merged) - 1++ if last >= 0 && !timeRange.From.After(merged[last].To) {+ if timeRange.To.After(merged[last].To) {+ merged[last].To = timeRange.To+ }++ continue+ }++ merged = append(merged, timeRange)+ }++ return merged+}diff --git a/backend/internal/features/backups/backups/core/physical/chain_view/restore_coverage_test.go b/backend/internal/features/backups/backups/core/physical/chain_view/restore_coverage_test.gonew file mode 100644index 00000000..40f09191--- /dev/null+++ b/backend/internal/features/backups/backups/core/physical/chain_view/restore_coverage_test.go@@ -0,0 +1,298 @@+package chain_view_test++import (+ "testing"+ "time"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "databasus-backend/internal/features/backups/backups/core/physical/chain_view"+ physical_enums "databasus-backend/internal/features/backups/backups/core/physical/enums"+ physical_models "databasus-backend/internal/features/backups/backups/core/physical/models"+ physical_testing "databasus-backend/internal/features/backups/backups/core/physical/testing"+ "databasus-backend/internal/util/walmath"+)++// An incremental's start and stop sit inside one segment, as they do in a real+// chain.+const incrementalLSNSpan = walmath.LSN(0x100)++func Test_GetRestoreCoverage_WhenNoFullBackupCompleted_ReturnsEmptyCoverage(t *testing.T) {+ t.Parallel()++ prereqs := createChainViewTestPrereqs(t)+ clock := newRestoreClock()+ seedCoverageSegment(t, prereqs, 1, clock.at(5))++ coverage := getRestoreCoverage(t, prereqs)++ assert.Nil(t, coverage.LatestRestorableAt)+ assert.NotNil(t, coverage.RestorableRanges)+ assert.Empty(t, coverage.RestorableRanges)+ assert.Empty(t, coverage.BlockingGaps)+}++func Test_GetRestoreCoverage_WhenWalIsContiguous_ReturnsOneRangeUpToNewestSegment(t *testing.T) {+ t.Parallel()++ prereqs := createChainViewTestPrereqs(t)+ clock := newRestoreClock()++ seedCoverageFull(t, prereqs, 0, clock.at(0))+ seedCoverageSegment(t, prereqs, 1, clock.at(5))+ seedCoverageSegment(t, prereqs, 2, clock.at(10))++ coverage := getRestoreCoverage(t, prereqs)++ assertRestorableRanges(t, coverage, [][2]time.Time{{clock.at(0), clock.at(10)}})+ assert.Empty(t, coverage.BlockingGaps)+}++func Test_GetRestoreCoverage_WhenGapHasNoIncrementalAfterIt_EndsAtGapAndReportsItBlocking(t *testing.T) {+ t.Parallel()++ prereqs := createChainViewTestPrereqs(t)+ clock := newRestoreClock()++ seedCoverageFull(t, prereqs, 0, clock.at(0))+ seedCoverageSegment(t, prereqs, 1, clock.at(5))+ seedCoverageSegment(t, prereqs, 3, clock.at(15))++ coverage := getRestoreCoverage(t, prereqs)++ assertRestorableRanges(t, coverage, [][2]time.Time{{clock.at(0), clock.at(5)}})+ assert.Equal(t, []chain_view.LSNRange{{Start: lsnAt(2), End: lsnAt(3)}}, coverage.BlockingGaps)+}++func Test_GetRestoreCoverage_WhenCompletedIncrementalBridgesGap_ReturnsTwoRangesWithoutBlockingGap(t *testing.T) {+ t.Parallel()++ prereqs := createChainViewTestPrereqs(t)+ clock := newRestoreClock()++ full := seedCoverageFull(t, prereqs, 0, clock.at(0))+ seedCoverageSegment(t, prereqs, 1, clock.at(5))+ seedCoverageIncremental(t, prereqs, full, lsnAt(3), clock.at(20), physical_enums.PhysicalBackupStatusCompleted)+ seedCoverageSegment(t, prereqs, 3, clock.at(25))+ seedCoverageSegment(t, prereqs, 4, clock.at(30))++ coverage := getRestoreCoverage(t, prereqs)++ assertRestorableRanges(t, coverage, [][2]time.Time{+ {clock.at(0), clock.at(5)},+ {clock.at(20), clock.at(30)},+ })+ assert.Empty(t, coverage.BlockingGaps, "the incremental after the gap bridges it")+}++func Test_GetRestoreCoverage_WhenIncrementalCompletedBeforeGap_KeepsGapBlocking(t *testing.T) {+ t.Parallel()++ prereqs := createChainViewTestPrereqs(t)+ clock := newRestoreClock()++ full := seedCoverageFull(t, prereqs, 0, clock.at(0))+ seedCoverageIncremental(t, prereqs, full, lsnAt(1), clock.at(3), physical_enums.PhysicalBackupStatusCompleted)+ seedCoverageSegment(t, prereqs, 1, clock.at(5))+ seedCoverageSegment(t, prereqs, 3, clock.at(15))++ coverage := getRestoreCoverage(t, prereqs)++ assertRestorableRanges(t, coverage, [][2]time.Time{{clock.at(0), clock.at(5)}})+ assert.Equal(t, []chain_view.LSNRange{{Start: lsnAt(2), End: lsnAt(3)}}, coverage.BlockingGaps)+}++func Test_GetRestoreCoverage_WhenIncrementalAfterGapIsNotCompleted_KeepsGapBlocking(t *testing.T) {+ t.Parallel()++ for _, status := range []physical_enums.PhysicalBackupStatus{+ physical_enums.PhysicalBackupStatusError,+ physical_enums.PhysicalBackupStatusChainBroken,+ physical_enums.PhysicalBackupStatusInProgress,+ } {+ t.Run(string(status), func(t *testing.T) {+ t.Parallel()++ prereqs := createChainViewTestPrereqs(t)+ clock := newRestoreClock()++ full := seedCoverageFull(t, prereqs, 0, clock.at(0))+ seedCoverageSegment(t, prereqs, 1, clock.at(5))+ seedCoverageIncremental(t, prereqs, full, lsnAt(3), clock.at(20), status)+ seedCoverageSegment(t, prereqs, 3, clock.at(25))++ coverage := getRestoreCoverage(t, prereqs)++ assertRestorableRanges(t, coverage, [][2]time.Time{{clock.at(0), clock.at(5)}})+ assert.Equal(t, []chain_view.LSNRange{{Start: lsnAt(2), End: lsnAt(3)}}, coverage.BlockingGaps)+ })+ }+}++func Test_GetRestoreCoverage_WhenIncrementalBridgesOnlyFirstOfTwoGaps_ReportsSecondGapBlocking(t *testing.T) {+ t.Parallel()++ prereqs := createChainViewTestPrereqs(t)+ clock := newRestoreClock()++ full := seedCoverageFull(t, prereqs, 0, clock.at(0))+ seedCoverageSegment(t, prereqs, 1, clock.at(5))+ seedCoverageIncremental(t, prereqs, full, lsnAt(3), clock.at(20), physical_enums.PhysicalBackupStatusCompleted)+ seedCoverageSegment(t, prereqs, 3, clock.at(25))+ seedCoverageSegment(t, prereqs, 5, clock.at(40))++ coverage := getRestoreCoverage(t, prereqs)++ assertRestorableRanges(t, coverage, [][2]time.Time{+ {clock.at(0), clock.at(5)},+ {clock.at(20), clock.at(25)},+ })+ assert.Equal(t, []chain_view.LSNRange{{Start: lsnAt(4), End: lsnAt(5)}}, coverage.BlockingGaps)+}++func Test_GetRestoreCoverage_WhenIncrementalStopsInsideMissingSegment_ReturnsPointRangeAndBlockingGap(t *testing.T) {+ t.Parallel()++ prereqs := createChainViewTestPrereqs(t)+ clock := newRestoreClock()++ full := seedCoverageFull(t, prereqs, 0, clock.at(0))+ seedCoverageSegment(t, prereqs, 1, clock.at(5))+ seedCoverageIncremental(t, prereqs, full, lsnAt(2)+physical_testing.FirstRecordOffset, clock.at(10),+ physical_enums.PhysicalBackupStatusCompleted)+ seedCoverageSegment(t, prereqs, 3, clock.at(15))++ coverage := getRestoreCoverage(t, prereqs)++ assertRestorableRanges(t, coverage, [][2]time.Time{+ {clock.at(0), clock.at(5)},+ {clock.at(10), clock.at(10)},+ })+ assert.Equal(t, []chain_view.LSNRange{{Start: lsnAt(2), End: lsnAt(3)}}, coverage.BlockingGaps,+ "the WAL right after the incremental is missing, so the restore cannot move past it")+}++func Test_GetRestoreCoverage_WhenSegmentIsStillUploading_EndsRangeBeforeIt(t *testing.T) {+ t.Parallel()++ prereqs := createChainViewTestPrereqs(t)+ clock := newRestoreClock()++ seedCoverageFull(t, prereqs, 0, clock.at(0))+ seedCoverageSegment(t, prereqs, 1, clock.at(5))+ uploadingSegment := physical_testing.NewTestWalSegment(prereqs.database.ID, prereqs.storage.ID, 1,+ walmath.WalSegmentNo(2).GetFilename(1), lsnAt(2), lsnAt(3))+ uploadingSegment.FileName = nil+ uploadingSegment.ReceivedAt = clock.at(10)+ physical_testing.CreateTestWalSegment(t, uploadingSegment)+ seedCoverageSegment(t, prereqs, 3, clock.at(15))++ coverage := getRestoreCoverage(t, prereqs)++ assertRestorableRanges(t, coverage, [][2]time.Time{{clock.at(0), clock.at(5)}})+ assert.Empty(t, coverage.BlockingGaps,+ "an uploading segment is no gap; the verdict waits for the archive progress point instead")+}++func Test_GetRestoreCoverage_WhenNewerFullCompleted_StartsRangesAtNewerFull(t *testing.T) {+ t.Parallel()++ prereqs := createChainViewTestPrereqs(t)+ clock := newRestoreClock()++ olderFull := seedCoverageFull(t, prereqs, 0, clock.at(0))+ seedCoverageSegment(t, prereqs, 1, clock.at(5))+ seedCoverageIncremental(t, prereqs, olderFull, lsnAt(3), clock.at(20), physical_enums.PhysicalBackupStatusCompleted)+ seedCoverageSegment(t, prereqs, 3, clock.at(25))++ newerFull := physical_testing.NewTestCompletedFullBackup(+ prereqs.database.ID, prereqs.storage.ID, 1, lsnAt(5), lsnAt(6))+ newerFull.CompletedAt = new(clock.at(30))+ newerFull.CreatedAt = olderFull.CreatedAt.Add(time.Second)+ physical_testing.CreateTestFullBackup(t, newerFull)+ seedCoverageSegment(t, prereqs, 6, clock.at(35))++ coverage := getRestoreCoverage(t, prereqs)++ assertRestorableRanges(t, coverage, [][2]time.Time{{clock.at(30), clock.at(35)}})+ assert.Empty(t, coverage.BlockingGaps, "the older chain's gap is not the newest chain's")+}++func getRestoreCoverage(t *testing.T, prereqs *chainViewTestPrereqs) *chain_view.RestoreCoverage {+ t.Helper()++ coverage, err := chain_view.GetChainViewService().GetRestoreCoverage(prereqs.database.ID)+ require.NoError(t, err)++ return coverage+}++// Checks the ranges and that the last one ends where a latest restore reaches.+func assertRestorableRanges(t *testing.T, coverage *chain_view.RestoreCoverage, expected [][2]time.Time) {+ t.Helper()++ require.Len(t, coverage.RestorableRanges, len(expected))++ for index, expectedRange := range expected {+ assert.WithinDuration(t, expectedRange[0], coverage.RestorableRanges[index].From, time.Millisecond,+ "range %d starts", index)+ assert.WithinDuration(t, expectedRange[1], coverage.RestorableRanges[index].To, time.Millisecond,+ "range %d ends", index)+ }++ require.NotNil(t, coverage.LatestRestorableAt)+ assert.WithinDuration(t, *coverage.LatestRestorableAt,+ coverage.RestorableRanges[len(coverage.RestorableRanges)-1].To, time.Millisecond,+ "the last range ends at the latest restorable moment")+}++func seedCoverageFull(+ t *testing.T,+ prereqs *chainViewTestPrereqs,+ segmentNo int,+ completedAt time.Time,+) *physical_models.PhysicalFullBackup {+ t.Helper()++ full := physical_testing.NewTestCompletedFullBackup(+ prereqs.database.ID, prereqs.storage.ID, 1, lsnAt(segmentNo), lsnAt(segmentNo+1))+ full.CompletedAt = &completedAt++ return physical_testing.CreateTestFullBackup(t, full)+}++func seedCoverageIncremental(+ t *testing.T,+ prereqs *chainViewTestPrereqs,+ full *physical_models.PhysicalFullBackup,+ startLSN walmath.LSN,+ completedAt time.Time,+ status physical_enums.PhysicalBackupStatus,+) *physical_models.PhysicalIncrementalBackup {+ t.Helper()++ incremental := physical_testing.NewTestCompletedIncrementalBackup(+ prereqs.database.ID, prereqs.storage.ID, full.ID, nil, 1, startLSN, startLSN+incrementalLSNSpan)+ incremental.Status = status+ incremental.CompletedAt = &completedAt++ if status == physical_enums.PhysicalBackupStatusInProgress {+ incremental.StopLSN = nil+ incremental.CompletedAt = nil+ }++ return physical_testing.CreateTestIncrementalBackup(t, incremental)+}++func seedCoverageSegment(+ t *testing.T,+ prereqs *chainViewTestPrereqs,+ segmentNo int,+ receivedAt time.Time,+) *physical_models.PhysicalWalSegment {+ t.Helper()++ return seedWalSegment(t, prereqs, walmath.WalSegmentNo(segmentNo).GetFilename(1),+ lsnAt(segmentNo), lsnAt(segmentNo+1), receivedAt)+}diff --git a/backend/internal/features/backups/backups/core/physical/chain_view/restore_set.go b/backend/internal/features/backups/backups/core/physical/chain_view/restore_set.goindex 7cde1ad2..3da5157d 100644--- a/backend/internal/features/backups/backups/core/physical/chain_view/restore_set.go+++ b/backend/internal/features/backups/backups/core/physical/chain_view/restore_set.go@@ -42,6 +42,49 @@ func (s *ChainViewService) ResolveRestoreSet(databaseID uuid.UUID,targetTime *time.Time,) (*RestoreSet, error) {+ reach, err := s.resolveRestoreReach(databaseID, targetTime)+ if err != nil {+ return nil, err+ }++ // A target later than the furthest point we can actually replay to means a+ // WAL gap (or simply missing WAL) sits before it. Refuse loudly; the caller+ // surfaces reachableLSN as the latest restorable point.+ if targetTime != nil && targetTime.After(reach.reachableTime) {+ return nil, WalGapBeforeTargetError{LatestRestorableLSN: reach.reachableLSN}+ }++ historyFiles, err := s.walHistoryRepository.FindAllByDatabase(databaseID)+ if err != nil {+ return nil, err+ }++ return &RestoreSet{+ RootFull: reach.chain.RootFull,+ Incrementals: reach.incrementals,+ WalSegments: reach.walRun,+ HistoryFiles: historyFiles,+ LastIncludedStopLSN: reach.lastStopLSN,+ MaxReplayableLSN: reach.reachableLSN,+ }, nil+}++type restoreReach struct {+ chain *ChainView+ incrementals []*physical_models.PhysicalIncrementalBackup+ lastStopLSN walmath.LSN+ walSegments []*physical_models.PhysicalWalSegment+ walRun []*physical_models.PhysicalWalSegment+ reachableLSN walmath.LSN+ reachableTime time.Time+}++// resolveRestoreReach picks the chain and backups for targetTime (nil ⇒ latest)+// and walks the WAL after the last of them up to the first gap.+func (s *ChainViewService) resolveRestoreReach(+ databaseID uuid.UUID,+ targetTime *time.Time,+) (*restoreReach, error) {candidates, err := s.orderedRestoreCandidates(databaseID)if err != nil {return nil, err@@ -70,25 +113,14 @@ func (s *ChainViewService) ResolveRestoreSet(walRun, reachableLSN, reachableTime := contiguousWalRun(restoreWalSegments, lastStopLSN, lastBackupTime)- // A target later than the furthest point we can actually replay to means a- // WAL gap (or simply missing WAL) sits before it. Refuse loudly; the caller- // surfaces reachableLSN as the latest restorable point.- if targetTime != nil && targetTime.After(reachableTime) {- return nil, WalGapBeforeTargetError{LatestRestorableLSN: reachableLSN}- }-- historyFiles, err := s.walHistoryRepository.FindAllByDatabase(databaseID)- if err != nil {- return nil, err- }-- return &RestoreSet{- RootFull: chain.RootFull,- Incrementals: incrementals,- WalSegments: walRun,- HistoryFiles: historyFiles,- LastIncludedStopLSN: lastStopLSN,- MaxReplayableLSN: reachableLSN,+ return &restoreReach{+ chain: chain,+ incrementals: incrementals,+ lastStopLSN: lastStopLSN,+ walSegments: restoreWalSegments,+ walRun: walRun,+ reachableLSN: reachableLSN,+ reachableTime: reachableTime,}, nil}diff --git a/backend/internal/features/backups/backups/core/physical/chain_view/service.go b/backend/internal/features/backups/backups/core/physical/chain_view/service.goindex 03510b56..af544aeb 100644--- a/backend/internal/features/backups/backups/core/physical/chain_view/service.go+++ b/backend/internal/features/backups/backups/core/physical/chain_view/service.go@@ -44,29 +44,6 @@ func (s *ChainViewService) FindLastExtendableChainByDatabase(databaseID uuid.UUIreturn newestView, nil}-// GetNewestCompletedFullWithGaps returns the newest completed full backup,-// whether or not its chain is still extendable, with the WAL gaps of its chain;-// nil when no full backup has completed. A chain broken by an incremental still-// has a full backup and can still have a gap, which FindLastExtendableChainByDatabase-// would hide.-func (s *ChainViewService) GetNewestCompletedFullWithGaps(databaseID uuid.UUID) (*FullBackupWithGaps, error) {- fulls, err := s.fullBackupRepository.FindCompletedNewestFirstByDatabase(databaseID)- if err != nil {- return nil, err- }-- if len(fulls) == 0 {- return nil, nil- }-- walGaps, err := s.FindWalGapsInChain(fulls[0].ID)- if err != nil {- return nil, err- }-- return &FullBackupWithGaps{FullBackup: fulls[0], WalGaps: walGaps}, nil-}-func (s *ChainViewService) FindNonExtendableChainsByDatabase(databaseID uuid.UUID) ([]*ChainView, error) {fulls, err := s.fullBackupRepository.FindCompletedNewestFirstByDatabase(databaseID)if err != nil {@@ -124,8 +101,14 @@ func (s *ChainViewService) FindWalGapsInChain(rootFullBackupID uuid.UUID) ([]LSNreturn nil, err}+ return findGapsBetweenSegments(segments), nil+}++// findGapsBetweenSegments lists the holes between consecutive segments ordered+// by start_lsn; nil for fewer than two segments.+func findGapsBetweenSegments(segments []*physical_models.PhysicalWalSegment) []LSNRange {if len(segments) < 2 {- return nil, nil+ return nil}gaps := make([]LSNRange, 0)@@ -142,7 +125,7 @@ func (s *ChainViewService) FindWalGapsInChain(rootFullBackupID uuid.UUID) ([]LSN}}- return gaps, nil+ return gaps}func (s *ChainViewService) CheckHistoryFilePresence(diff --git a/backend/internal/features/backups/backups/core/physical/chain_view/view.go b/backend/internal/features/backups/backups/core/physical/chain_view/view.goindex 414a5085..a7162079 100644--- a/backend/internal/features/backups/backups/core/physical/chain_view/view.go+++ b/backend/internal/features/backups/backups/core/physical/chain_view/view.go@@ -17,11 +17,6 @@ type ChainView struct {Span LSNRange}-type FullBackupWithGaps struct {- FullBackup *physical_models.PhysicalFullBackup- WalGaps []LSNRange-}-// LSNMax is the unbounded upper sentinel for the latest chain on a timeline// (no successor FULL exists). Encoded as the maximum uint64 LSN so range// predicates against pg_lsn columns still work without a special case.diff --git a/backend/internal/features/backups/backups/core/physical/service/dto.go b/backend/internal/features/backups/backups/core/physical/service/dto.goindex af80e82c..a3a8fe58 100644--- a/backend/internal/features/backups/backups/core/physical/service/dto.go+++ b/backend/internal/features/backups/backups/core/physical/service/dto.go@@ -126,7 +126,7 @@ type WalStreamStatisticsQuery struct {SlotRebuildLagBytes int64IsStreamingExpected boolHasCompletedFullBackup bool- NewestChainGaps []chain_view.LSNRange+ RestoreBlockingGaps []chain_view.LSNRangeNow time.Time}diff --git a/backend/internal/features/backups/backups/core/physical/service/wal_stream_statistics.go b/backend/internal/features/backups/backups/core/physical/service/wal_stream_statistics.goindex a3e4d704..dd4b24c0 100644--- a/backend/internal/features/backups/backups/core/physical/service/wal_stream_statistics.go+++ b/backend/internal/features/backups/backups/core/physical/service/wal_stream_statistics.go@@ -62,7 +62,7 @@ func (s *PhysicalBackupService) GetWalStreamStatistics(query WalStreamStatisticsSlotRebuildLagBytes: query.SlotRebuildLagBytes,IsStreamingExpected: query.IsStreamingExpected,HasCompletedFullBackup: query.HasCompletedFullBackup,- NewestChainGaps: query.NewestChainGaps,+ RestoreBlockingGaps: query.RestoreBlockingGaps,Now: query.Now,}),KeepingUp: wal_health.GetKeepingUp(recentSamples, query.SlotRebuildLagBytes, query.Now),diff --git a/backend/internal/features/backups/backups/core/physical/wal_health/dto.go b/backend/internal/features/backups/backups/core/physical/wal_health/dto.goindex 553ac10d..878d4235 100644--- a/backend/internal/features/backups/backups/core/physical/wal_health/dto.go+++ b/backend/internal/features/backups/backups/core/physical/wal_health/dto.go@@ -25,8 +25,9 @@ type VerdictInput struct {IsStreamingExpected boolHasCompletedFullBackup bool- // The WAL gaps of the newest completed full backup's chain.- NewestChainGaps []chain_view.LSNRange+ // The WAL gaps of the newest chain that the latest restore cannot cross.+ // A gap a completed incremental bridged is already left out.+ RestoreBlockingGaps []chain_view.LSNRangeNow time.Time}diff --git a/backend/internal/features/backups/backups/core/physical/wal_health/verdict.go b/backend/internal/features/backups/backups/core/physical/wal_health/verdict.goindex 38081901..49880cb3 100644--- a/backend/internal/features/backups/backups/core/physical/wal_health/verdict.go+++ b/backend/internal/features/backups/backups/core/physical/wal_health/verdict.go@@ -225,7 +225,7 @@ func getWalChainBrokenReason(input VerdictInput, samples verdictSamples) *Reasonreturn nil}- for _, gap := range input.NewestChainGaps {+ for _, gap := range input.RestoreBlockingGaps {if gap.End <= *newest.ArchiveProgressLSN {return &Reason{Code: ReasonCodeWalChainBroken, Level: ReasonLevelBroken}}diff --git a/backend/internal/features/backups/backups/core/physical/wal_health/verdict_test.go b/backend/internal/features/backups/backups/core/physical/wal_health/verdict_test.goindex d955c8e3..898e9151 100644--- a/backend/internal/features/backups/backups/core/physical/wal_health/verdict_test.go+++ b/backend/internal/features/backups/backups/core/physical/wal_health/verdict_test.go@@ -518,7 +518,7 @@ func Test_GetVerdict_WhenChainHasGap_ListsWalChainBrokenOnlyForGapBelowProgressPname: "Slot rebuilt",buildInput: func() VerdictInput {input := newTestVerdictInput(buildTestSamples(0, nil))- input.NewestChainGaps = []chain_view.LSNRange{gapBelowProgressPoint}+ input.RestoreBlockingGaps = []chain_view.LSNRange{gapBelowProgressPoint}return input},@@ -536,7 +536,7 @@ func Test_GetVerdict_WhenChainHasGap_ListsWalChainBrokenOnlyForGapBelowProgressPname: "gap above the archive progress point",buildInput: func() VerdictInput {input := newTestVerdictInput(buildTestSamples(0, nil))- input.NewestChainGaps = []chain_view.LSNRange{gapAboveProgressPoint}+ input.RestoreBlockingGaps = []chain_view.LSNRange{gapAboveProgressPoint}return input},diff --git a/backend/internal/features/backups/backups/dto/physical/wal_stream_live.go b/backend/internal/features/backups/backups/dto/physical/wal_stream_live.gonew file mode 100644index 00000000..90b820bf--- /dev/null+++ b/backend/internal/features/backups/backups/dto/physical/wal_stream_live.go@@ -0,0 +1,36 @@+package backups_dto_physical++import (+ "time"++ physical_enums "databasus-backend/internal/features/backups/backups/core/physical/enums"+)++// The current values of a database's running WAL stream, read at the time of+// the request and never stored. Current is null while no streamer runs.+type GetWalStreamLiveResponse struct {+ IsStreamerRunning bool `json:"isStreamerRunning"`+ Current *WalStreamLive `json:"current"`+}++type WalStreamLive struct {+ MeasuredAt time.Time `json:"measuredAt"`++ // The newest probe of the source, made at least every 10 seconds; null until+ // the streaming session's first probe. The source-side values below are null+ // unless that probe found the source reachable with its slot.+ SourceProbedAt *time.Time `json:"sourceProbedAt"`+ SourceState *physical_enums.PhysicalWalStreamSourceState `json:"sourceState"`+ SourceCurrentLsn *string `json:"sourceCurrentLsn"`+ SlotWalStatus *string `json:"slotWalStatus"`+ SlotLagBytes *int64 `json:"slotLagBytes"`+ SlotSafeWalSizeBytes *int64 `json:"slotSafeWalSizeBytes"`++ ArchiveProgressLsn *string `json:"archiveProgressLsn"`+ LastArchivedWalAt *time.Time `json:"lastArchivedWalAt"`+ UnarchivedWalBytes *int64 `json:"unarchivedWalBytes"`++ LocalQueueBytes int64 `json:"localQueueBytes"`+ LocalQueuePauseBytes int64 `json:"localQueuePauseBytes"`+ IsReceiverRunning bool `json:"isReceiverRunning"`+}diff --git a/backend/internal/features/backups/backups/dto/physical/wal_stream_statistics.go b/backend/internal/features/backups/backups/dto/physical/wal_stream_statistics.goindex 5136a9fa..35e18e65 100644--- a/backend/internal/features/backups/backups/dto/physical/wal_stream_statistics.go+++ b/backend/internal/features/backups/backups/dto/physical/wal_stream_statistics.go@@ -40,13 +40,28 @@ type GetWalStreamStatisticsRequest struct {// its name, every time is UTC, and the verdict, states, reasons and notices are// codes, never display text.type GetWalStreamStatisticsResponse struct {- Health WalStreamHealth `json:"health"`+ Health WalStreamHealth `json:"health"`++ // The moment a restore to the latest available point reaches; null while no+ // full backup has completed.+ LatestRestorableAt *time.Time `json:"latestRestorableAt"`++ // The stretches of time the newest chain can restore to, oldest first; the+ // last one ends at latestRestorableAt. Empty while no full backup has+ // completed.+ RestorableRanges []WalStreamTimeRange `json:"restorableRanges"`+Streamer WalStreamStreamer `json:"streamer"`Current *WalStreamCurrent `json:"current"`KeepingUp wal_health.KeepingUp `json:"keepingUp"`Series WalStreamSeries `json:"series"`}+type WalStreamTimeRange struct {+ From time.Time `json:"from"`+ To time.Time `json:"to"`+}+type WalStreamHealth struct {Level wal_health.HealthLevel `json:"level"`Reasons []wal_health.Reason `json:"reasons"`diff --git a/backend/internal/features/backups/backups/services/di.go b/backend/internal/features/backups/backups/services/di.goindex 09dd3911..627d87e7 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.GetPhysicalWalStreamSupervisor(),backups_download.GetRestoreStreamWriter(),backups_download.GetRestoreTokenService(),encryption_secrets.GetSecretKeyService(),diff --git a/backend/internal/features/backups/backups/services/physical_service.go b/backend/internal/features/backups/backups/services/physical_service.goindex 21c74122..5bdfb22b 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+ walStreamSupervisor *backuping_physical.PhysicalWalStreamSupervisorrestoreStreamWriter *restore_stream.WriterrestoreTokenService *restore_token.ServicesecretKeyService *encryption_secrets.SecretKeyServicediff --git a/backend/internal/features/backups/backups/services/physical_wal_stream_live.go b/backend/internal/features/backups/backups/services/physical_wal_stream_live.gonew file mode 100644index 00000000..1cf9cd04--- /dev/null+++ b/backend/internal/features/backups/backups/services/physical_wal_stream_live.go@@ -0,0 +1,69 @@+package backups_services++import (+ "context"+ "time"++ "github.com/google/uuid"++ backups_dto_physical "databasus-backend/internal/features/backups/backups/dto/physical"+ usecases_physical_postgresql "databasus-backend/internal/features/backups/backups/usecases/physical/postgresql"+ "databasus-backend/internal/features/databases"+ users_models "databasus-backend/internal/features/users/models"+)++// GetWalStreamLive returns the current values of a physical PostgreSQL+// database's running WAL stream to a user who can view it. It reads the+// streamer's memory and opens no connection to the source.+func (s *PhysicalBackupService) GetWalStreamLive(+ ctx context.Context,+ user *users_models.User,+ databaseID uuid.UUID,+) (*backups_dto_physical.GetWalStreamLiveResponse, error) {+ database, err := s.databaseService.GetDatabase(ctx, user, databaseID)+ if err != nil {+ return nil, err+ }++ if database.Type != databases.DatabaseTypePostgresPhysical {+ return nil, ErrWalStreamStatisticsNotPhysical+ }++ liveState, isRunning := s.walStreamSupervisor.GetLiveState(databaseID, time.Now().UTC())+ if !isRunning {+ return &backups_dto_physical.GetWalStreamLiveResponse{}, nil+ }++ return &backups_dto_physical.GetWalStreamLiveResponse{+ IsStreamerRunning: true,+ Current: toWalStreamLive(liveState),+ }, nil+}++func toWalStreamLive(+ liveState *usecases_physical_postgresql.WalStreamLiveState,+) *backups_dto_physical.WalStreamLive {+ live := &backups_dto_physical.WalStreamLive{+ MeasuredAt: liveState.MeasuredAt.UTC(),+ SourceProbedAt: getTimeInUTC(liveState.SourceProbedAt),+ SourceState: liveState.SourceState,+ SlotWalStatus: liveState.SlotWalStatus,+ SlotLagBytes: liveState.SlotLagBytes,+ SlotSafeWalSizeBytes: liveState.SlotSafeWalSizeBytes,+ LastArchivedWalAt: getTimeInUTC(liveState.LastArchivedWalAt),+ UnarchivedWalBytes: liveState.UnarchivedWalBytes,+ LocalQueueBytes: liveState.LocalQueueBytes,+ LocalQueuePauseBytes: liveState.LocalQueuePauseBytes,+ IsReceiverRunning: liveState.IsReceiverRunning,+ }++ if liveState.SourceCurrentLSN != nil {+ live.SourceCurrentLsn = new(liveState.SourceCurrentLSN.String())+ }++ if liveState.ArchiveProgressLSN != nil {+ live.ArchiveProgressLsn = new(liveState.ArchiveProgressLSN.String())+ }++ return live+}diff --git a/backend/internal/features/backups/backups/services/physical_wal_stream_statistics.go b/backend/internal/features/backups/backups/services/physical_wal_stream_statistics.goindex 1d3e6335..0190d505 100644--- a/backend/internal/features/backups/backups/services/physical_wal_stream_statistics.go+++ b/backend/internal/features/backups/backups/services/physical_wal_stream_statistics.go@@ -7,6 +7,7 @@ import ("github.com/google/uuid"+ "databasus-backend/internal/features/backups/backups/core/physical/chain_view"physical_dto "databasus-backend/internal/features/backups/backups/core/physical/dto"physical_enums "databasus-backend/internal/features/backups/backups/core/physical/enums"physical_core_service "databasus-backend/internal/features/backups/backups/core/physical/service"@@ -52,7 +53,7 @@ func (s *PhysicalBackupService) GetWalStreamStatistics(return nil, err}- newestFull, err := s.chainViewService.GetNewestCompletedFullWithGaps(databaseID)+ restoreCoverage, err := s.chainViewService.GetRestoreCoverage(databaseID)if err != nil {return nil, err}@@ -71,9 +72,9 @@ func (s *PhysicalBackupService) GetWalStreamStatistics(Now: time.Now().UTC(),}- if newestFull != nil {+ if restoreCoverage.LatestRestorableAt != nil {query.HasCompletedFullBackup = true- query.NewestChainGaps = newestFull.WalGaps+ query.RestoreBlockingGaps = restoreCoverage.BlockingGaps}statistics, err := s.physicalCoreService.GetWalStreamStatistics(query)@@ -81,7 +82,11 @@ func (s *PhysicalBackupService) GetWalStreamStatistics(return nil, err}- return toWalStreamStatisticsResponse(request.Period, bucketDuration, isFullBackupPending, statistics), nil+ response := toWalStreamStatisticsResponse(request.Period, bucketDuration, isFullBackupPending, statistics)+ response.LatestRestorableAt = getTimeInUTC(restoreCoverage.LatestRestorableAt)+ response.RestorableRanges = toWalStreamTimeRanges(restoreCoverage.RestorableRanges)++ return response, nil}// Databasus requests a full backup by itself only after a slot rebuild, so the@@ -216,3 +221,16 @@ func getSeriesPointsInUTC(return points}++func toWalStreamTimeRanges(timeRanges []chain_view.TimeRange) []backups_dto_physical.WalStreamTimeRange {+ responseRanges := make([]backups_dto_physical.WalStreamTimeRange, 0, len(timeRanges))++ for _, timeRange := range timeRanges {+ responseRanges = append(responseRanges, backups_dto_physical.WalStreamTimeRange{+ From: timeRange.From.UTC(),+ To: timeRange.To.UTC(),+ })+ }++ return responseRanges+}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_lsn_watcher.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_lsn_watcher.goindex 1d8700f9..2a8f85f7 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_lsn_watcher.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/slot_lsn_watcher.go@@ -94,9 +94,18 @@ func (p slotProbe) IsReachableWithSlot() bool {return p.Outcome == slotProbeOutcomeReachable}+// Every probe is remembered with its time, so the live state can show the+// source as of the newest probe without connecting to it again.+func (s *WalStreamSupervisor) probeSlot(ctx context.Context, logger *slog.Logger) slotProbe {+ probe := s.inspectSourceSlot(ctx, logger)+ s.latestProbe.Store(&timedSlotProbe{probe: probe, probedAt: time.Now().UTC()})++ return probe+}+// A source that accepts connections but never answers would otherwise hold// every caller's tick for as long as the TCP connection lives.-func (s *WalStreamSupervisor) probeSlot(ctx context.Context, logger *slog.Logger) slotProbe {+func (s *WalStreamSupervisor) inspectSourceSlot(ctx context.Context, logger *slog.Logger) slotProbe {probeCtx, cancel := context.WithTimeout(ctx, slotProbeTimeout)defer cancel()diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_live_state.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_live_state.gonew file mode 100644index 00000000..89ca4ab2--- /dev/null+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_live_state.go@@ -0,0 +1,94 @@+package usecases_physical_postgresql++import (+ "time"++ physical_enums "databasus-backend/internal/features/backups/backups/core/physical/enums"+ "databasus-backend/internal/util/walmath"+)++// WalStreamLiveState is what the running streamer knows at one moment, read+// without storing anything. The source-side values are those of the newest slot+// probe, which the liveness watcher makes at least every 10 seconds.+type WalStreamLiveState struct {+ MeasuredAt time.Time++ // Nil until the session's first probe; the source-side fields below are nil+ // unless that probe found the source reachable with its slot.+ SourceProbedAt *time.Time+ SourceState *physical_enums.PhysicalWalStreamSourceState+ SourceCurrentLSN *walmath.LSN+ SlotWalStatus *string+ SlotLagBytes *int64+ SlotSafeWalSizeBytes *int64++ // Nil while nothing has been archived for the database.+ ArchiveProgressLSN *walmath.LSN+ LastArchivedWalAt *time.Time++ // Nil without a source position or an archive progress point; zero once the+ // progress point passes the probed position.+ UnarchivedWalBytes *int64++ LocalQueueBytes int64+ LocalQueuePauseBytes int64+ IsReceiverRunning bool+}++type timedSlotProbe struct {+ probe slotProbe+ probedAt time.Time+}++// GetLiveState never takes the upload snapshot or the restart counters, which+// reset on read and belong to the next sample. The archive progress point and+// the unsaved amount are derived the way the sample derives them.+func (s *WalStreamSupervisor) GetLiveState(now time.Time) WalStreamLiveState {+ liveState := WalStreamLiveState{+ MeasuredAt: now,+ LocalQueueBytes: s.backlogBytes(),+ LocalQueuePauseBytes: s.highWatermarkBytes.Load(),+ IsReceiverRunning: s.isReceiverRunning(),+ }++ newestCommitted, lastCommittedWalAt := s.getLastCommittedWal(s.logger)+ archiveProgressLSN := getArchiveProgressPoint(s.getLowestQueuedSegment(), newestCommitted)++ if archiveProgressLSN > 0 {+ liveState.ArchiveProgressLSN = &archiveProgressLSN+ }++ liveState.LastArchivedWalAt = lastCommittedWalAt++ latestProbe := s.latestProbe.Load()+ if latestProbe == nil {+ return liveState+ }++ sourceState := getSampleSourceState(latestProbe.probe)+ liveState.SourceProbedAt = &latestProbe.probedAt+ liveState.SourceState = &sourceState++ if !latestProbe.probe.IsReachableWithSlot() {+ return liveState+ }++ slotState := latestProbe.probe.State+ liveState.SourceCurrentLSN = &slotState.CurrentLSN+ liveState.SlotWalStatus = &slotState.WalStatus+ liveState.SlotLagBytes = &slotState.LagBytes+ liveState.SlotSafeWalSizeBytes = slotState.SafeWalSizeBytes++ // The probe can be up to one watcher interval old while segments keep+ // landing, so the progress point may pass the probed position. Everything+ // the source had written by then is saved, which is zero, not unknown.+ if archiveProgressLSN > 0 {+ liveState.UnarchivedWalBytes = new(int64(0))++ if slotState.CurrentLSN > archiveProgressLSN {+ liveState.UnarchivedWalBytes = new(int64(slotState.CurrentLSN - archiveProgressLSN))+ }+ }++ return liveState+}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_live_state_test.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_live_state_test.gonew file mode 100644index 00000000..d0667ae3--- /dev/null+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_live_state_test.go@@ -0,0 +1,100 @@+package usecases_physical_postgresql++import (+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ physical_enums "databasus-backend/internal/features/backups/backups/core/physical/enums"+ physical_repositories "databasus-backend/internal/features/backups/backups/core/physical/repositories"+ postgresql_physical "databasus-backend/internal/features/databases/databases/postgresql/physical"+ "databasus-backend/internal/util/logger"+ "databasus-backend/internal/util/walmath"+)++const liveStateQueuedStartLSN = walmath.LSN(0x40000000)++func Test_GetLiveState_WhenSourceProbed_ReportsValuesOfNewestProbe(t *testing.T) {+ supervisor := newLiveStateTestSupervisor(t)+ probedAt := time.Now().UTC().Add(-7 * time.Second)++ supervisor.latestProbe.Store(&timedSlotProbe{+ probe: slotProbe{Outcome: slotProbeOutcomeReachable, State: &SlotState{+ WalStatus: "reserved",+ LagBytes: 1024 * 1024,+ CurrentLSN: liveStateQueuedStartLSN + 5*1024*1024,+ }},+ probedAt: probedAt,+ })++ liveState := supervisor.GetLiveState(time.Now().UTC())++ require.NotNil(t, liveState.SourceProbedAt)+ assert.Equal(t, probedAt, *liveState.SourceProbedAt, "source values carry the time of the probe they come from")+ assert.Equal(t, physical_enums.PhysicalWalStreamSourceStateReachable, *liveState.SourceState)+ assert.Equal(t, int64(1024*1024), *liveState.SlotLagBytes)+ assert.Equal(t, "reserved", *liveState.SlotWalStatus)+ assert.Equal(t, liveStateQueuedStartLSN, *liveState.ArchiveProgressLSN,+ "the lowest queued segment holds the progress point back, as in a sample")+ assert.Equal(t, int64(5*1024*1024), *liveState.UnarchivedWalBytes)+}++func Test_GetLiveState_WhenArchiveProgressPassedOlderProbe_ReportsNothingUnsaved(t *testing.T) {+ supervisor := newLiveStateTestSupervisor(t)+ supervisor.latestProbe.Store(&timedSlotProbe{+ probe: slotProbe{Outcome: slotProbeOutcomeReachable, State: &SlotState{+ WalStatus: "reserved",+ CurrentLSN: liveStateQueuedStartLSN - 1024,+ }},+ probedAt: time.Now().UTC().Add(-9 * time.Second),+ })++ liveState := supervisor.GetLiveState(time.Now().UTC())++ require.NotNil(t, liveState.UnarchivedWalBytes,+ "segments saved after the probe must not make the unsaved amount unknown")+ assert.Equal(t, int64(0), *liveState.UnarchivedWalBytes)+}++func Test_GetLiveState_WhenSourceUnreachable_ReportsStateWithoutSourceValues(t *testing.T) {+ supervisor := newLiveStateTestSupervisor(t)+ supervisor.latestProbe.Store(&timedSlotProbe{+ probe: slotProbe{Outcome: slotProbeOutcomeUnreachable},+ probedAt: time.Now().UTC(),+ })++ liveState := supervisor.GetLiveState(time.Now().UTC())++ assert.Equal(t, physical_enums.PhysicalWalStreamSourceStateUnreachable, *liveState.SourceState)+ assert.Nil(t, liveState.SlotLagBytes)+ assert.Nil(t, liveState.SourceCurrentLSN)+ assert.Nil(t, liveState.UnarchivedWalBytes)+}++func Test_GetLiveState_WhenRead_LeavesRestartCountsForTheNextSample(t *testing.T) {+ supervisor := newLiveStateTestSupervisor(t)+ supervisor.receiverRespawns.recordRespawn(false)++ supervisor.GetLiveState(time.Now().UTC())++ restarts, _ := supervisor.receiverRespawns.takeCounts()+ assert.Equal(t, 1, restarts, "a live reading must not consume what the sample reports")+}++func newLiveStateTestSupervisor(t *testing.T) *WalStreamSupervisor {+ t.Helper()++ supervisor := NewWalStreamSupervisor(WalStreamSpec{+ DatabaseID: uuid.New(),+ SourceDB: &postgresql_physical.PostgresqlPhysicalDatabase{ReplicationSlotName: "databasus_live_test"},+ WalSegmentRepo: physical_repositories.GetWalSegmentRepository(),+ WatchDirRoot: t.TempDir(),+ Logger: logger.GetLogger(),+ })+ supervisor.setLowestQueuedSegment([]queuedWalSegment{{timelineID: 1, startLSN: liveStateQueuedStartLSN}})++ return supervisor+}diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream.goindex 22de9f4a..eea5b07a 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/wal_stream.go@@ -243,6 +243,9 @@ type WalStreamSupervisor struct {// Written by the uploader dispatcher, read by the lag monitor (wal_staleness.go).lowestQueuedSegmentMutex sync.MutexlowestQueuedSegment *walPosition++ // The newest slot probe of any caller, read by GetLiveState.+ latestProbe atomic.Pointer[timedSlotProbe]}func NewWalStreamSupervisor(spec WalStreamSpec) *WalStreamSupervisor {diff --git a/frontend/src/entity/backups/physical/api/physicalWalStreamStatisticsApi.ts b/frontend/src/entity/backups/physical/api/physicalWalStreamStatisticsApi.tsindex 08c3b7d1..645619c6 100644--- a/frontend/src/entity/backups/physical/api/physicalWalStreamStatisticsApi.ts+++ b/frontend/src/entity/backups/physical/api/physicalWalStreamStatisticsApi.ts@@ -1,5 +1,6 @@import { getApplicationServer } from '../../../../constants';import { apiHelper } from '../../../../shared/api/apiHelper';+import type { WalStreamLiveResponse } from '../model/WalStreamLiveResponse';import type { WalStreamStatistics } from '../model/WalStreamStatistics';import type { WalStreamStatisticsPeriod } from '../model/WalStreamStatisticsPeriod';@@ -14,4 +15,12 @@ export const physicalWalStreamStatisticsApi = {`${getApplicationServer()}/api/v1/backups/physical/database/${databaseId}/wal-stream/statistics?${params.toString()}`,);},++ // Read every second while the tab is visible, so a failed request is simply replaced by the next+ // one instead of being retried.+ async getWalStreamLive(databaseId: string) {+ return apiHelper.fetchGetJson<WalStreamLiveResponse>(+ `${getApplicationServer()}/api/v1/backups/physical/database/${databaseId}/wal-stream/live`,+ );+ },};diff --git a/frontend/src/entity/backups/physical/index.ts b/frontend/src/entity/backups/physical/index.tsindex 2da1bf30..9226854e 100644--- a/frontend/src/entity/backups/physical/index.ts+++ b/frontend/src/entity/backups/physical/index.ts@@ -36,6 +36,9 @@ export type { WalStreamKeepingUp } from './model/WalStreamKeepingUp';export type { WalStreamSeriesPoint } from './model/WalStreamSeriesPoint';export type { WalStreamSeries } from './model/WalStreamSeries';export type { WalStreamStatistics } from './model/WalStreamStatistics';+export type { WalStreamTimeRange } from './model/WalStreamTimeRange';+export type { WalStreamLive } from './model/WalStreamLive';+export type { WalStreamLiveResponse } from './model/WalStreamLiveResponse';export { WAL_STREAM_STATISTICS_PERIOD_LABEL_KEYS } from './model/WalStreamStatisticsPeriodLabelKeys';export { WAL_STREAM_HEALTH_LEVEL_LABEL_KEYS } from './model/WalStreamHealthLevelLabelKeys';export { WAL_STREAM_REASON_LEVEL_LABEL_KEYS } from './model/WalStreamReasonLevelLabelKeys';diff --git a/frontend/src/entity/backups/physical/model/WalStreamLive.ts b/frontend/src/entity/backups/physical/model/WalStreamLive.tsnew file mode 100644index 00000000..d23e2f9f--- /dev/null+++ b/frontend/src/entity/backups/physical/model/WalStreamLive.ts@@ -0,0 +1,23 @@+import type { WalStreamSourceState } from './WalStreamSourceState';++// The running streamer's values at one moment, never stored. The source-side values come from the+// streamer's newest probe of the source, made at least every 10 seconds; they are null until that+// probe found the source reachable with its slot.+export interface WalStreamLive {+ measuredAt: string;++ sourceProbedAt: string | null;+ sourceState: WalStreamSourceState | null;+ sourceCurrentLsn: string | null;+ slotWalStatus: string | null;+ slotLagBytes: number | null;+ slotSafeWalSizeBytes: number | null;++ archiveProgressLsn: string | null;+ lastArchivedWalAt: string | null;+ unarchivedWalBytes: number | null;++ localQueueBytes: number;+ localQueuePauseBytes: number;+ isReceiverRunning: boolean;+}diff --git a/frontend/src/entity/backups/physical/model/WalStreamLiveResponse.ts b/frontend/src/entity/backups/physical/model/WalStreamLiveResponse.tsnew file mode 100644index 00000000..4c79b543--- /dev/null+++ b/frontend/src/entity/backups/physical/model/WalStreamLiveResponse.ts@@ -0,0 +1,7 @@+import type { WalStreamLive } from './WalStreamLive';++// Current is null while no streamer runs for the database.+export interface WalStreamLiveResponse {+ isStreamerRunning: boolean;+ current: WalStreamLive | null;+}diff --git a/frontend/src/entity/backups/physical/model/WalStreamStatistics.ts b/frontend/src/entity/backups/physical/model/WalStreamStatistics.tsindex 5d8dfecc..671db762 100644--- a/frontend/src/entity/backups/physical/model/WalStreamStatistics.ts+++ b/frontend/src/entity/backups/physical/model/WalStreamStatistics.ts@@ -3,9 +3,19 @@ import type { WalStreamHealth } from './WalStreamHealth';import type { WalStreamKeepingUp } from './WalStreamKeepingUp';import type { WalStreamSeries } from './WalStreamSeries';import type { WalStreamStreamer } from './WalStreamStreamer';+import type { WalStreamTimeRange } from './WalStreamTimeRange';export interface WalStreamStatistics {health: WalStreamHealth;++ // The moment a restore to the latest available point reaches; null while no full backup has+ // completed.+ latestRestorableAt: string | null;++ // The stretches of time the newest chain can restore to, oldest first; the last one ends at+ // latestRestorableAt. Empty while no full backup has completed.+ restorableRanges: WalStreamTimeRange[];+streamer: WalStreamStreamer;current: WalStreamCurrent | null;keepingUp: WalStreamKeepingUp;diff --git a/frontend/src/entity/backups/physical/model/WalStreamTimeRange.ts b/frontend/src/entity/backups/physical/model/WalStreamTimeRange.tsnew file mode 100644index 00000000..bc3c5015--- /dev/null+++ b/frontend/src/entity/backups/physical/model/WalStreamTimeRange.ts@@ -0,0 +1,4 @@+export interface WalStreamTimeRange {+ from: string;+ to: string;+}diff --git a/frontend/src/features/backups/physical/monitoring/lib/chartRows.test.ts b/frontend/src/features/backups/physical/monitoring/lib/chartRows.test.tsindex 8e55155f..cb088004 100644--- a/frontend/src/features/backups/physical/monitoring/lib/chartRows.test.ts+++ b/frontend/src/features/backups/physical/monitoring/lib/chartRows.test.ts@@ -5,7 +5,15 @@ import {type WalStreamSeriesPoint,WalStreamStatisticsPeriod,} from '../../../../../entity/backups/physical';-import { getDataSinceMs, hasAnyChartValues, toChartRows } from './chartRows';+import {+ getBinaryAxisTicks,+ getChartTimeDomain,+ getDataSinceMs,+ getMissingDataRanges,+ getRowsMaximum,+ hasEnoughChartPoints,+ toChartRows,+} from './chartRows';// The entity's public API imports its API client, and the client's config module reads window at// import time. The tests run in node, so they supply window.@@ -87,15 +95,132 @@ describe('toChartRows', () => {});});-describe('hasAnyChartValues', () => {- it('reports no history when no point has values', () => {- expect(hasAnyChartValues(buildSeries([buildEmptyPoint(0), buildEmptyPoint(1)]))).toBe(false);+describe('hasEnoughChartPoints', () => {+ it('draws no chart from three points with values', () => {+ const series = buildSeries([+ buildEmptyPoint(0),+ buildFallingBehindPoint(1),+ buildFallingBehindPoint(2),+ buildFallingBehindPoint(3),+ ]);++ expect(hasEnoughChartPoints(series)).toBe(false);+ });++ it('draws a chart from four points with values', () => {+ const series = buildSeries([0, 1, 2, 3].map(buildFallingBehindPoint));++ expect(hasEnoughChartPoints(series)).toBe(true);+ });+});++describe('getChartTimeDomain', () => {+ it('starts the axis at the first point with values when the data starts inside the period', () => {+ const series = buildSeries([+ buildEmptyPoint(0),+ buildEmptyPoint(1),+ buildFallingBehindPoint(2),+ ]);++ expect(getChartTimeDomain(series)).toEqual([+ seriesStartMs + 2 * 60_000,+ new Date(series.to).getTime(),+ ]);+ });++ it('spans the whole period when the data covers it', () => {+ const series = buildSeries([buildFallingBehindPoint(0), buildFallingBehindPoint(1)]);++ expect(getChartTimeDomain(series)).toEqual([+ new Date(series.from).getTime(),+ new Date(series.to).getTime(),+ ]);+ });+});++const KiB = 1024;+const MiB = 1024 * KiB;+const GiB = 1024 * MiB;++describe('getBinaryAxisTicks', () => {+ it('keeps the minimum top of 1 MiB for a quiet database, with quarter steps', () => {+ expect(getBinaryAxisTicks(2 * KiB, MiB)).toEqual([0, 256 * KiB, 512 * KiB, 768 * KiB, MiB]);+ });++ it('ends on a whole unit above the data', () => {+ expect(getBinaryAxisTicks(3.7 * MiB, MiB)).toEqual([0, MiB, 2 * MiB, 3 * MiB, 4 * MiB]);+ });++ it('steps in round numbers of the unit for a large amount', () => {+ expect(getBinaryAxisTicks(520 * MiB, 512 * MiB)).toEqual([0, 200 * MiB, 400 * MiB, 600 * MiB]);});- it('reports history once one point has values', () => {- expect(hasAnyChartValues(buildSeries([buildEmptyPoint(0), buildFallingBehindPoint(1)]))).toBe(- true,+ it('switches to gigabytes above 1 GiB', () => {+ expect(getBinaryAxisTicks(1.5 * GiB, MiB)).toEqual([0, 0.5 * GiB, GiB, 1.5 * GiB]);+ });++ it('still draws an axis when there is neither data nor a minimum', () => {+ expect(getBinaryAxisTicks(0, 0)).toEqual([0, 0.25, 0.5, 0.75, 1]);+ });++ it('always reaches the data maximum', () => {+ for (const dataMaximum of [1, 999, 1025, 17 * MiB, 3 * GiB + 1]) {+ const ticks = getBinaryAxisTicks(dataMaximum, 0);++ expect(ticks[ticks.length - 1]).toBeGreaterThanOrEqual(dataMaximum);+ expect(ticks.length).toBeLessThanOrEqual(7);+ }+ });+});++describe('getRowsMaximum', () => {+ it('takes the largest value of the given lines and skips gaps', () => {+ const rows = toChartRows([buildFallingBehindPoint(0), buildEmptyPoint(1)]);++ expect(getRowsMaximum(rows, ['sourceWriteBytesPerSecond', 'archiveBytesPerSecond'])).toBe(+ 21 * MB,+ );+ });++ it('is zero without values', () => {+ expect(getRowsMaximum(toChartRows([buildEmptyPoint(0)]), ['archiveBytesPerSecond'])).toBe(0);+ });+});++describe('getMissingDataRanges', () => {+ const buildPoints = (emptyMinutes: number[], count = 10) =>+ Array.from({ length: count }, (_, minute) =>+ emptyMinutes.includes(minute) ? buildEmptyPoint(minute) : buildFallingBehindPoint(minute),);++ it('finds nothing in a full series', () => {+ expect(getMissingDataRanges(buildSeries(buildPoints([])))).toEqual([]);+ });++ it('finds five empty minutes in the middle, ending where data comes back', () => {+ expect(getMissingDataRanges(buildSeries(buildPoints([3, 4, 5, 6, 7])))).toEqual([+ { fromMs: seriesStartMs + 3 * 60_000, toMs: seriesStartMs + 8 * 60_000 },+ ]);+ });++ it('ignores a single empty point, which is usually the interval still being measured', () => {+ expect(getMissingDataRanges(buildSeries(buildPoints([4, 9])))).toEqual([]);+ });++ it('does not count the time before the data starts', () => {+ expect(getMissingDataRanges(buildSeries(buildPoints([0, 1, 2])))).toEqual([]);+ });++ it('ends a run at the end of the period when the data stops', () => {+ const series = buildSeries(buildPoints([8, 9]));++ expect(getMissingDataRanges(series)).toEqual([+ { fromMs: seriesStartMs + 8 * 60_000, toMs: new Date(series.to).getTime() },+ ]);+ });++ it('finds nothing in a series without values', () => {+ expect(getMissingDataRanges(buildSeries([buildEmptyPoint(0), buildEmptyPoint(1)]))).toEqual([]);});});diff --git a/frontend/src/features/backups/physical/monitoring/lib/chartRows.ts b/frontend/src/features/backups/physical/monitoring/lib/chartRows.tsindex e76bbeaf..317af424 100644--- a/frontend/src/features/backups/physical/monitoring/lib/chartRows.ts+++ b/frontend/src/features/backups/physical/monitoring/lib/chartRows.ts@@ -1,4 +1,5 @@import type { WalStreamSeries, WalStreamSeriesPoint } from '../../../../../entity/backups/physical';+import type { MissingDataRange } from '../model/MissingDataRange';import type { WalStreamChartRow } from '../model/WalStreamChartRow';export const toChartRows = (points: WalStreamSeriesPoint[]): WalStreamChartRow[] =>@@ -23,8 +24,99 @@ const hasPointValues = (point: WalStreamSeriesPoint): boolean =>point.sourceWriteBytesPerSecond !== null ||point.maxLocalQueueBytes !== null;-export const hasAnyChartValues = (series: WalStreamSeries): boolean =>- series.points.some(hasPointValues);+// Fewer points than this draw a line that says nothing, such as one start-up burst falling to zero.+const MIN_CHART_POINTS = 4;++export const hasEnoughChartPoints = (series: WalStreamSeries): boolean =>+ series.points.filter(hasPointValues).length >= MIN_CHART_POINTS;++// The axis starts where the data starts, so a few minutes of data are not squeezed against the end+// of a whole hour.+export const getChartTimeDomain = (series: WalStreamSeries): [number, number] => [+ getDataSinceMs(series) ?? new Date(series.from).getTime(),+ new Date(series.to).getTime(),+];++const BYTES_PER_UNIT = 1024;+const TARGET_AXIS_INTERVALS = 4;+const NICE_STEP_FACTORS = [1, 2, 2.5, 5, 10];++// Round ticks for an amount axis, in the binary unit formatBytes shows them in, so the axis reads+// 256 KB, 512 KB, 768 KB rather than 293 KB, 585.9 KB, 878.9 KB. The minimum top is a floor, so a+// quiet database draws a line near the bottom instead of noise scaled up to fill the chart.+export const getBinaryAxisTicks = (dataMaximum: number, minimumTop: number): number[] => {+ const top = Math.max(dataMaximum, minimumTop, 1);++ const unitPower = Math.max(0, Math.floor(Math.log(top) / Math.log(BYTES_PER_UNIT)));+ const unit = BYTES_PER_UNIT ** unitPower;+ const topInUnits = top / unit;++ const roughStep = topInUnits / TARGET_AXIS_INTERVALS;+ const magnitude = 10 ** Math.floor(Math.log10(roughStep));+ const stepFactor =+ NICE_STEP_FACTORS.find((factor) => factor * magnitude >= roughStep) ?? NICE_STEP_FACTORS[4];+ const step = stepFactor * magnitude;++ // Rounding first keeps a float error from adding an interval to an exact top such as 1 MiB; the+ // check in bytes then adds one when the data sits just above the rounded top.+ let intervals = Math.round(topInUnits / step);++ if (intervals * step * unit < top) {+ intervals++;+ }++ return Array.from({ length: intervals + 1 }, (_, index) => index * step * unit);+};++// The largest value the given lines reach, 0 for a chart without values.+export const getRowsMaximum = (+ rows: WalStreamChartRow[],+ dataKeys: (keyof WalStreamChartRow)[],+): number =>+ rows.reduce(+ (maximum, row) =>+ dataKeys.reduce((rowMaximum, dataKey) => Math.max(rowMaximum, row[dataKey] ?? 0), maximum),+ 0,+ );++const MIN_MISSING_POINTS = 2;++// Runs of points without values after the data starts. One empty point is usually the interval+// still being measured, so a run needs two. Each range ends where the next point with values+// starts, or at the end of the period.+export const getMissingDataRanges = (series: WalStreamSeries): MissingDataRange[] => {+ const firstIndexWithValues = series.points.findIndex(hasPointValues);++ if (firstIndexWithValues === -1) {+ return [];+ }++ const ranges: MissingDataRange[] = [];+ let runStartIndex: number | null = null;++ const closeRun = (endIndex: number, toMs: number) => {+ if (runStartIndex !== null && endIndex - runStartIndex >= MIN_MISSING_POINTS) {+ ranges.push({ fromMs: new Date(series.points[runStartIndex].startedAt).getTime(), toMs });+ }++ runStartIndex = null;+ };++ for (let index = firstIndexWithValues; index < series.points.length; index++) {+ const point = series.points[index];++ if (!hasPointValues(point)) {+ runStartIndex ??= index;+ continue;+ }++ closeRun(index, new Date(point.startedAt).getTime());+ }++ closeRun(series.points.length, new Date(series.to).getTime());++ return ranges;+};// Null when the data covers the whole period, so the caption only appears when the charts start// later than their axis.diff --git a/frontend/src/features/backups/physical/monitoring/lib/clockFormat.ts b/frontend/src/features/backups/physical/monitoring/lib/clockFormat.tsnew file mode 100644index 00000000..97dcc1c5--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/lib/clockFormat.ts@@ -0,0 +1,5 @@+import { getUserTimeFormat } from '../../../../../shared/time';++/* eslint-disable i18next/no-literal-string -- dayjs format tokens, not copy */+export const getClockFormat = (): string => (getUserTimeFormat().use12Hours ? 'h:mm A' : 'HH:mm');+/* eslint-enable i18next/no-literal-string */diff --git a/frontend/src/features/backups/physical/monitoring/lib/fullBackupAction.test.ts b/frontend/src/features/backups/physical/monitoring/lib/fullBackupAction.test.tsnew file mode 100644index 00000000..1138d3ed--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/lib/fullBackupAction.test.ts@@ -0,0 +1,118 @@+import { describe, expect, it, vi } from 'vitest';++import {+ WalStreamHealthLevel,+ WalStreamReasonCode,+ WalStreamReasonLevel,+} from '../../../../../entity/backups/physical';+import { FullBackupAction } from '../model/FullBackupAction';+import { getFullBackupAction } from './fullBackupAction';++// The entity's public API imports its API client, and the client's config module reads window at+// import time. The tests run in node, so they supply window.+vi.hoisted(() => {+ vi.stubGlobal('window', {});+});++const brokenChainInput = {+ level: WalStreamHealthLevel.BROKEN,+ isStateConfirmed: true,+ reasons: [{ code: WalStreamReasonCode.WAL_CHAIN_BROKEN, level: WalStreamReasonLevel.BROKEN }],+ latestRestorableAt: '2026-10-18T07:50:00Z',+ isFullBackupPending: false,+ isCanManageDBs: true,+ isRequestingFullBackup: false,+};++describe('getFullBackupAction', () => {+ it('offers a full backup for a broken chain', () => {+ expect(getFullBackupAction(brokenChainInput)).toBe(FullBackupAction.AVAILABLE);+ });++ it('offers a full backup for a missing slot', () => {+ const action = getFullBackupAction({+ ...brokenChainInput,+ reasons: [{ code: WalStreamReasonCode.SLOT_MISSING, level: WalStreamReasonLevel.BROKEN }],+ });++ expect(action).toBe(FullBackupAction.AVAILABLE);+ });++ it('offers a full backup to a healthy database without a completed full backup', () => {+ const action = getFullBackupAction({+ ...brokenChainInput,+ level: WalStreamHealthLevel.HEALTHY,+ reasons: [],+ latestRestorableAt: null,+ });++ expect(action).toBe(FullBackupAction.AVAILABLE);+ });++ it('hides the button from a user who cannot manage the database', () => {+ expect(getFullBackupAction({ ...brokenChainInput, isCanManageDBs: false })).toBe(+ FullBackupAction.HIDDEN,+ );+ });++ it('hides the button when no reason calls for a full backup', () => {+ const action = getFullBackupAction({+ ...brokenChainInput,+ level: WalStreamHealthLevel.NEEDS_ATTENTION,+ reasons: [+ {+ code: WalStreamReasonCode.LOCAL_QUEUE_FILLING,+ level: WalStreamReasonLevel.NEEDS_ATTENTION,+ },+ ],+ });++ expect(action).toBe(FullBackupAction.HIDDEN);+ });++ it.each([WalStreamHealthLevel.NOT_STREAMING, WalStreamHealthLevel.COLLECTING_DATA])(+ 'hides the button for %s even without a completed full backup',+ (level) => {+ const action = getFullBackupAction({+ ...brokenChainInput,+ level,+ reasons: [],+ latestRestorableAt: null,+ });++ expect(action).toBe(FullBackupAction.HIDDEN);+ },+ );++ it('hides the button while the current state cannot be confirmed', () => {+ expect(getFullBackupAction({ ...brokenChainInput, isStateConfirmed: false })).toBe(+ FullBackupAction.HIDDEN,+ );+ });++ it('hides the button while a full backup is requested or running', () => {+ expect(getFullBackupAction({ ...brokenChainInput, isFullBackupPending: true })).toBe(+ FullBackupAction.HIDDEN,+ );+ });++ it('shows the request as running while it is sent', () => {+ expect(getFullBackupAction({ ...brokenChainInput, isRequestingFullBackup: true })).toBe(+ FullBackupAction.REQUESTING,+ );+ });++ it('offers the button again once a failed request settles', () => {+ const whileRequesting = getFullBackupAction({+ ...brokenChainInput,+ isRequestingFullBackup: true,+ });+ const afterFailure = getFullBackupAction({+ ...brokenChainInput,+ isRequestingFullBackup: false,+ });++ expect(whileRequesting).toBe(FullBackupAction.REQUESTING);+ expect(afterFailure).toBe(FullBackupAction.AVAILABLE);+ });+});diff --git a/frontend/src/features/backups/physical/monitoring/lib/fullBackupAction.ts b/frontend/src/features/backups/physical/monitoring/lib/fullBackupAction.tsnew file mode 100644index 00000000..bd2a569b--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/lib/fullBackupAction.ts@@ -0,0 +1,47 @@+import {+ WalStreamHealthLevel,+ type WalStreamReason,+ WalStreamReasonCode,+} from '../../../../../entity/backups/physical';+import { FullBackupAction } from '../model/FullBackupAction';++interface FullBackupActionInput {+ level: WalStreamHealthLevel;+ isStateConfirmed: boolean;+ reasons: WalStreamReason[];+ latestRestorableAt: string | null;+ isFullBackupPending: boolean;+ isCanManageDBs: boolean;+ isRequestingFullBackup: boolean;+}++// Not streaming takes no backups at all, and collecting data lasts two minutes at most, so neither+// offers a full backup.+const LEVELS_OFFERING_FULL_BACKUP = new Set([+ WalStreamHealthLevel.HEALTHY,+ WalStreamHealthLevel.NEEDS_ATTENTION,+ WalStreamHealthLevel.BROKEN,+]);++const REASONS_REPAIRED_BY_FULL_BACKUP = new Set([+ WalStreamReasonCode.WAL_CHAIN_BROKEN,+ WalStreamReasonCode.SLOT_MISSING,+]);++// Pending needs no state of its own: the backend stores the request before it answers, so the+// refresh after a successful request already reports the full backup as pending.+export const getFullBackupAction = (input: FullBackupActionInput): FullBackupAction => {+ if (!input.isCanManageDBs || !input.isStateConfirmed || input.isFullBackupPending) {+ return FullBackupAction.HIDDEN;+ }++ if (!LEVELS_OFFERING_FULL_BACKUP.has(input.level) || !isFullBackupTheFix(input)) {+ return FullBackupAction.HIDDEN;+ }++ return input.isRequestingFullBackup ? FullBackupAction.REQUESTING : FullBackupAction.AVAILABLE;+};++const isFullBackupTheFix = (input: FullBackupActionInput): boolean =>+ input.latestRestorableAt === null ||+ input.reasons.some((reason) => REASONS_REPAIRED_BY_FULL_BACKUP.has(reason.code));diff --git a/frontend/src/features/backups/physical/monitoring/lib/fullBackupRequestController.test.ts b/frontend/src/features/backups/physical/monitoring/lib/fullBackupRequestController.test.tsnew file mode 100644index 00000000..907cced3--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/lib/fullBackupRequestController.test.ts@@ -0,0 +1,101 @@+import { describe, expect, it, vi } from 'vitest';++import {+ type FullBackupRequestDependencies,+ FullBackupRequestController,+} from './fullBackupRequestController';++const createDeferredRequest = () => {+ let resolveRequest: () => void = () => {};+ let rejectRequest: (error: unknown) => void = () => {};++ const promise = new Promise<void>((resolve, reject) => {+ resolveRequest = resolve;+ rejectRequest = reject;+ });++ return { promise, resolveRequest, rejectRequest };+};++const createRequestController = (requestFullBackup: () => Promise<unknown>) => {+ const dependencies: FullBackupRequestDependencies = {+ requestFullBackup: vi.fn(requestFullBackup),+ refreshNow: vi.fn(),+ reportRequested: vi.fn(),+ reportError: vi.fn(),+ };+ const requestingStates: boolean[] = [];+ const controller = new FullBackupRequestController(dependencies, (isRequesting) =>+ requestingStates.push(isRequesting),+ );++ return { controller, dependencies, requestingStates };+};++describe('FullBackupRequestController', () => {+ it('frees a busy button on the first landed refresh even when it never sent the request', () => {+ const { controller, requestingStates } = createRequestController(() => Promise.resolve());++ controller.handleRefreshLanded();++ expect(requestingStates).toEqual([false]);+ });++ it('refreshes after a successful request and keeps the button busy until that refresh lands', async () => {+ const { controller, dependencies, requestingStates } = createRequestController(() =>+ Promise.resolve(),+ );++ await controller.requestFullBackup();++ expect(dependencies.requestFullBackup).toHaveBeenCalledOnce();+ expect(dependencies.reportRequested).toHaveBeenCalledOnce();+ expect(dependencies.refreshNow).toHaveBeenCalledOnce();+ expect(requestingStates).toEqual([true]);++ controller.handleRefreshLanded();++ expect(requestingStates).toEqual([true, false]);+ });++ it('keeps the button busy when a scheduled refresh lands while the request is being sent', async () => {+ const deferredRequest = createDeferredRequest();+ const { controller, requestingStates } = createRequestController(() => deferredRequest.promise);++ const request = controller.requestFullBackup();+ controller.handleRefreshLanded();++ expect(requestingStates).toEqual([true]);++ deferredRequest.resolveRequest();+ await request;++ expect(requestingStates).toEqual([true]);+ });++ it('reports a failed request and frees the button at once', async () => {+ const refusal = new Error('refused');+ const { controller, dependencies, requestingStates } = createRequestController(() =>+ Promise.reject(refusal),+ );++ await controller.requestFullBackup();++ expect(dependencies.reportError).toHaveBeenCalledWith(refusal);+ expect(dependencies.reportRequested).not.toHaveBeenCalled();+ expect(dependencies.refreshNow).not.toHaveBeenCalled();+ expect(requestingStates).toEqual([true, false]);+ });++ it('ignores another press while the request is being sent', async () => {+ const deferredRequest = createDeferredRequest();+ const { controller, dependencies } = createRequestController(() => deferredRequest.promise);++ const firstRequest = controller.requestFullBackup();+ await controller.requestFullBackup();+ deferredRequest.resolveRequest();+ await firstRequest;++ expect(dependencies.requestFullBackup).toHaveBeenCalledOnce();+ });+});diff --git a/frontend/src/features/backups/physical/monitoring/lib/fullBackupRequestController.ts b/frontend/src/features/backups/physical/monitoring/lib/fullBackupRequestController.tsnew file mode 100644index 00000000..9f2083a8--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/lib/fullBackupRequestController.ts@@ -0,0 +1,54 @@+export interface FullBackupRequestDependencies {+ requestFullBackup: () => Promise<unknown>;+ refreshNow: () => void;+ reportRequested: () => void;+ reportError: (error: unknown) => void;+}++// Sends the full backup request and keeps the button busy until the screen can show the result.+// The backend stores the request before it answers, so after a success the refresh started here+// reports the full backup as pending; until that refresh lands the button must not come back. A+// scheduled refresh that lands while the request is still being sent frees nothing either. The+// class holds no React state, so the flow is testable without a DOM.+export class FullBackupRequestController {+ private isRequesting = false;+ private isRequestInFlight = false;++ constructor(+ private readonly dependencies: FullBackupRequestDependencies,+ private readonly onRequestingChange: (isRequesting: boolean) => void,+ ) {}++ async requestFullBackup() {+ if (this.isRequesting) {+ return;+ }++ this.setRequesting(true);+ this.isRequestInFlight = true;++ try {+ await this.dependencies.requestFullBackup();+ this.isRequestInFlight = false;+ this.dependencies.reportRequested();+ this.dependencies.refreshNow();+ } catch (e) {+ this.isRequestInFlight = false;+ this.dependencies.reportError(e);+ this.setRequesting(false);+ }+ }++ handleRefreshLanded() {+ if (!this.isRequestInFlight) {+ this.setRequesting(false);+ }+ }++ // Reports every change, even to the value it already holds: a controller created again after a+ // language switch starts idle, and its first landed refresh must still free a busy button.+ private setRequesting(isRequesting: boolean) {+ this.isRequesting = isRequesting;+ this.onRequestingChange(isRequesting);+ }+}diff --git a/frontend/src/features/backups/physical/monitoring/lib/keepingUpSentences.test.ts b/frontend/src/features/backups/physical/monitoring/lib/keepingUpSentences.test.tsindex 1bbb2cc2..17f36260 100644--- a/frontend/src/features/backups/physical/monitoring/lib/keepingUpSentences.test.ts+++ b/frontend/src/features/backups/physical/monitoring/lib/keepingUpSentences.test.ts@@ -85,13 +85,18 @@ describe('getKeepingUpSentences', () => {it.each([[WalStreamKeepingUpState.KEEPING_UP, 'backups.physical.monitoring.keepingUp.keepingUp'],[WalStreamKeepingUpState.IDLE, 'backups.physical.monitoring.keepingUp.idle'],- [WalStreamKeepingUpState.UNKNOWN, 'backups.physical.monitoring.keepingUp.unknown'],])('describes %s in one sentence', (state, expectedKey) => {expect(getKeepingUpSentences(buildKeepingUp({ state })).map((sentence) => sentence.key),).toEqual([expectedKey]);});+ it('adds no sentence while the state is unknown', () => {+ expect(+ getKeepingUpSentences(buildKeepingUp({ state: WalStreamKeepingUpState.UNKNOWN })),+ ).toEqual([]);+ });+it('says how much backlog is left and how long it takes while catching up', () => {const [sentence] = getKeepingUpSentences(buildKeepingUp({diff --git a/frontend/src/features/backups/physical/monitoring/lib/keepingUpSentences.ts b/frontend/src/features/backups/physical/monitoring/lib/keepingUpSentences.tsindex 9365f165..f5f8234b 100644--- a/frontend/src/features/backups/physical/monitoring/lib/keepingUpSentences.ts+++ b/frontend/src/features/backups/physical/monitoring/lib/keepingUpSentences.ts@@ -42,8 +42,9 @@ const getStateSentences = (keepingUp: WalStreamKeepingUp): MonitoringText[] => {case WalStreamKeepingUpState.IDLE:return [{ key: 'backups.physical.monitoring.keepingUp.idle' }];+ // The figures above already say "not measured", so an unknown state adds no sentence.default:- return [{ key: 'backups.physical.monitoring.keepingUp.unknown' }];+ return [];}};diff --git a/frontend/src/features/backups/physical/monitoring/lib/liveOverlay.test.ts b/frontend/src/features/backups/physical/monitoring/lib/liveOverlay.test.tsnew file mode 100644index 00000000..73c12805--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/lib/liveOverlay.test.ts@@ -0,0 +1,112 @@+import { describe, expect, it, vi } from 'vitest';++import { type WalStreamLive, WalStreamSourceState } from '../../../../../entity/backups/physical';+import { applyLiveValues } from './liveOverlay';+import { createTestWalStreamStatistics } from './testWalStreamStatistics';++// The entity's public API imports its API client, and the client's config module reads window at+// import time. The tests run in node, so they supply window.+vi.hoisted(() => {+ vi.stubGlobal('window', {});+});++const MiB = 1024 * 1024;++// The fixture's newest sample was taken at 11:59:48.+const buildLive = (overrides: Partial<WalStreamLive> = {}): WalStreamLive => ({+ measuredAt: '2026-10-18T11:59:59Z',+ sourceProbedAt: '2026-10-18T11:59:55Z',+ sourceState: WalStreamSourceState.REACHABLE,+ sourceCurrentLsn: '0/6000000',+ slotWalStatus: 'reserved',+ slotLagBytes: MiB,+ slotSafeWalSizeBytes: null,+ archiveProgressLsn: '0/5F00000',+ lastArchivedWalAt: '2026-10-18T11:59:57Z',+ unarchivedWalBytes: MiB,+ localQueueBytes: 300 * MiB,+ localQueuePauseBytes: 512 * MiB,+ isReceiverRunning: false,+ ...overrides,+});++describe('applyLiveValues', () => {+ it('keeps the statistics without live values', () => {+ const statistics = createTestWalStreamStatistics();++ expect(applyLiveValues(statistics, null)).toBe(statistics);+ });++ it('lays newer values over the newest sample and moves its time', () => {+ const overlaid = applyLiveValues(createTestWalStreamStatistics(), buildLive());++ expect(overlaid.current).toMatchObject({+ sampledAt: '2026-10-18T11:59:59Z',+ localQueueBytes: 300 * MiB,+ isReceiverRunning: false,+ lastArchivedWalAt: '2026-10-18T11:59:57Z',+ slotLagBytes: MiB,+ unarchivedWalBytes: MiB,+ });+ expect(overlaid.keepingUp.unarchivedWalBytes).toBe(MiB);+ });++ it('keeps the rates, the verdict and the series of the statistics', () => {+ const statistics = createTestWalStreamStatistics();+ const overlaid = applyLiveValues(statistics, buildLive());++ expect(overlaid.keepingUp.sourceWriteBytesPerSecond).toBe(+ statistics.keepingUp.sourceWriteBytesPerSecond,+ );+ expect(overlaid.health).toBe(statistics.health);+ expect(overlaid.series).toBe(statistics.series);+ });++ it('keeps the sample when the live values are older than it', () => {+ const statistics = createTestWalStreamStatistics();++ expect(applyLiveValues(statistics, buildLive({ measuredAt: '2026-10-18T11:59:40Z' }))).toBe(+ statistics,+ );+ });++ it('keeps the source values of the sample when the probe is older than the sample', () => {+ const statistics = createTestWalStreamStatistics();+ const overlaid = applyLiveValues(+ statistics,+ buildLive({ sourceProbedAt: '2026-10-18T11:59:40Z' }),+ );++ expect(overlaid.current?.localQueueBytes).toBe(300 * MiB);+ expect(overlaid.current?.slotLagBytes).toBe(statistics.current?.slotLagBytes);+ expect(overlaid.current?.unarchivedWalBytes).toBe(statistics.current?.unarchivedWalBytes);+ expect(overlaid.keepingUp).toBe(statistics.keepingUp);+ });++ it('keeps the last save of the sample while the streamer has archived nothing yet', () => {+ const statistics = createTestWalStreamStatistics();+ const overlaid = applyLiveValues(statistics, buildLive({ lastArchivedWalAt: null }));++ expect(overlaid.current?.lastArchivedWalAt).toBe(statistics.current?.lastArchivedWalAt);+ });++ it('moves the restore point and the end of the newest stretch with the live save time', () => {+ const overlaid = applyLiveValues(createTestWalStreamStatistics(), buildLive());++ expect(overlaid.latestRestorableAt).toBe('2026-10-18T11:59:57Z');+ expect(overlaid.restorableRanges).toEqual([+ { from: '2026-10-17T03:00:00Z', to: '2026-10-18T11:59:57Z' },+ ]);+ });++ it('keeps the restore point where a gap stopped it, short of the newest saved change', () => {+ const statistics = createTestWalStreamStatistics({+ latestRestorableAt: '2026-10-18T07:50:00Z',+ restorableRanges: [{ from: '2026-10-17T03:00:00Z', to: '2026-10-18T07:50:00Z' }],+ });+ const overlaid = applyLiveValues(statistics, buildLive());++ expect(overlaid.latestRestorableAt).toBe('2026-10-18T07:50:00Z');+ expect(overlaid.restorableRanges).toBe(statistics.restorableRanges);+ });+});diff --git a/frontend/src/features/backups/physical/monitoring/lib/liveOverlay.ts b/frontend/src/features/backups/physical/monitoring/lib/liveOverlay.tsnew file mode 100644index 00000000..a19523bc--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/lib/liveOverlay.ts@@ -0,0 +1,85 @@+import type { WalStreamLive, WalStreamStatistics } from '../../../../../entity/backups/physical';++const isNewer = (time: string | null, than: string): time is string =>+ time !== null && new Date(time).getTime() > new Date(than).getTime();++const isSameMoment = (a: string | null, b: string | null) =>+ a !== null && b !== null && new Date(a).getTime() === new Date(b).getTime();++// A restore that reached the newest saved change in the sample keeps reaching it as segments land,+// so the restore point follows the live save time instead of lagging the figures by up to one+// statistics refresh. A restore stopped short of it, at a gap, stays where the statistics put it.+const followRestorePoint = (+ statistics: WalStreamStatistics,+ liveLastArchivedWalAt: string | null,+): Pick<WalStreamStatistics, 'latestRestorableAt' | 'restorableRanges'> => {+ const { latestRestorableAt, restorableRanges, current } = statistics;++ if (+ latestRestorableAt === null ||+ !isSameMoment(latestRestorableAt, current?.lastArchivedWalAt ?? null) ||+ !isNewer(liveLastArchivedWalAt, latestRestorableAt)+ ) {+ return { latestRestorableAt, restorableRanges };+ }++ const lastIndex = restorableRanges.length - 1;++ return {+ latestRestorableAt: liveLastArchivedWalAt,+ restorableRanges: restorableRanges.map((range, index) =>+ index === lastIndex && isSameMoment(range.to, latestRestorableAt)+ ? { ...range, to: liveLastArchivedWalAt }+ : range,+ ),+ };+};++// Lays the running streamer's newer values over the newest sample, so the figures, the path of+// changes and the measured label move every second while the verdict, the rates and the charts+// keep the 30-second statistics. Source-side values replace the sample's only when their probe is+// newer than the sample: an older probe's position against a newer progress point would understate+// what is not saved yet.+export const applyLiveValues = (+ statistics: WalStreamStatistics,+ live: WalStreamLive | null,+): WalStreamStatistics => {+ const { current } = statistics;++ if (live === null || current === null || !isNewer(live.measuredAt, current.sampledAt)) {+ return statistics;+ }++ const overlaidCurrent = {+ ...current,+ sampledAt: live.measuredAt,+ localQueueBytes: live.localQueueBytes,+ localQueuePauseBytes: live.localQueuePauseBytes,+ isReceiverRunning: live.isReceiverRunning,+ archiveProgressLsn: live.archiveProgressLsn ?? current.archiveProgressLsn,+ lastArchivedWalAt: live.lastArchivedWalAt ?? current.lastArchivedWalAt,+ };+ let overlaidKeepingUp = statistics.keepingUp;++ if (isNewer(live.sourceProbedAt, current.sampledAt) && live.sourceState !== null) {+ overlaidCurrent.sourceState = live.sourceState;+ overlaidCurrent.sourceCurrentLsn = live.sourceCurrentLsn;+ overlaidCurrent.slotWalStatus = live.slotWalStatus;+ overlaidCurrent.slotLagBytes = live.slotLagBytes;+ overlaidCurrent.slotSafeWalSizeBytes = live.slotSafeWalSizeBytes;+ overlaidCurrent.unarchivedWalBytes = live.unarchivedWalBytes;++ overlaidKeepingUp = {+ ...statistics.keepingUp,+ unarchivedWalBytes: live.unarchivedWalBytes,+ slotLagBytes: live.slotLagBytes,+ };+ }++ return {+ ...statistics,+ ...followRestorePoint(statistics, live.lastArchivedWalAt),+ current: overlaidCurrent,+ keepingUp: overlaidKeepingUp,+ };+};diff --git a/frontend/src/features/backups/physical/monitoring/lib/monitoringFigures.test.ts b/frontend/src/features/backups/physical/monitoring/lib/monitoringFigures.test.tsnew file mode 100644index 00000000..42a6e919--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/lib/monitoringFigures.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it, vi } from 'vitest';++import {+ WalStreamHealthLevel,+ WalStreamKeepingUpState,+} from '../../../../../entity/backups/physical';+import { getMonitoringFigures } from './monitoringFigures';+import { createTestWalStreamStatistics } from './testWalStreamStatistics';++// The entity's public API imports its API client, and the client's config module reads window at+// import time. The tests run in node, so they supply window.+vi.hoisted(() => {+ vi.stubGlobal('window', {});+});++const MB = 1000 * 1000;++describe('getMonitoringFigures', () => {+ it('shows when the last change was saved, what waits and both rates for a busy healthy database', () => {+ const statistics = createTestWalStreamStatistics();++ const figures = getMonitoringFigures({+ ...statistics,+ current: statistics.current && {+ ...statistics.current,+ lastArchivedWalAt: '2026-10-18T11:59:45Z',+ },+ keepingUp: {+ ...statistics.keepingUp,+ unarchivedWalBytes: 20 * MB,+ sourceWriteBytesPerSecond: 10 * MB,+ archiveBytesPerSecond: 10 * MB,+ },+ });++ expect(figures).toEqual({+ lastSavedAt: '2026-10-18T11:59:45Z',+ waitingToBeSavedBytes: 20 * MB,+ writeBytesPerSecond: 10 * MB,+ saveBytesPerSecond: 10 * MB,+ });+ });++ it('leaves the rates unknown, not zero, when no sample of the window holds a write value', () => {+ const statistics = createTestWalStreamStatistics();++ const figures = getMonitoringFigures({+ ...statistics,+ keepingUp: {+ ...statistics.keepingUp,+ state: WalStreamKeepingUpState.UNKNOWN,+ sourceWriteBytesPerSecond: null,+ archiveBytesPerSecond: null,+ },+ });++ expect(figures?.writeBytesPerSecond).toBeNull();+ expect(figures?.saveBytesPerSecond).toBeNull();+ });++ it.each([WalStreamHealthLevel.COLLECTING_DATA, WalStreamHealthLevel.NOT_STREAMING])(+ 'shows no figures for %s',+ (level) => {+ const statistics = createTestWalStreamStatistics();++ expect(getMonitoringFigures({ ...statistics, health: { ...statistics.health, level } })).toBe(+ null,+ );+ },+ );+});diff --git a/frontend/src/features/backups/physical/monitoring/lib/monitoringFigures.ts b/frontend/src/features/backups/physical/monitoring/lib/monitoringFigures.tsnew file mode 100644index 00000000..849a4d2a--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/lib/monitoringFigures.ts@@ -0,0 +1,25 @@+import {+ WalStreamHealthLevel,+ type WalStreamStatistics,+} from '../../../../../entity/backups/physical';+import type { MonitoringFigures } from '../model/MonitoringFigures';++// The amounts come from the keeping-up summary rather than the newest sample, so the figures agree+// with the keeping-up sentence written under them.+export const getMonitoringFigures = (statistics: WalStreamStatistics): MonitoringFigures | null => {+ const { level } = statistics.health;++ if (+ level === WalStreamHealthLevel.COLLECTING_DATA ||+ level === WalStreamHealthLevel.NOT_STREAMING+ ) {+ return null;+ }++ return {+ lastSavedAt: statistics.current?.lastArchivedWalAt ?? null,+ waitingToBeSavedBytes: statistics.keepingUp.unarchivedWalBytes,+ writeBytesPerSecond: statistics.keepingUp.sourceWriteBytesPerSecond,+ saveBytesPerSecond: statistics.keepingUp.archiveBytesPerSecond,+ };+};diff --git a/frontend/src/features/backups/physical/monitoring/lib/monitoringTextValues.ts b/frontend/src/features/backups/physical/monitoring/lib/monitoringTextValues.tsindex 0beb9f28..4397994c 100644--- a/frontend/src/features/backups/physical/monitoring/lib/monitoringTextValues.ts+++ b/frontend/src/features/backups/physical/monitoring/lib/monitoringTextValues.ts@@ -1,9 +1,12 @@+import dayjs from 'dayjs';import type { TFunction } from 'i18next';import { type LocaleContextValue, translateLocalizedText } from '../../../../../shared/i18n';import { formatBytes } from '../../../../../shared/lib';+import { getUserTimeFormat } from '../../../../../shared/time';import type { MonitoringText } from '../model/MonitoringText';import type { MonitoringTextParam } from '../model/MonitoringTextParam';+import { getClockFormat } from './clockFormat';// Runs while a component renders, with that render's language, and turns the numbers and nested// keys of a sentence into the values its translation interpolates.@@ -44,5 +47,10 @@ const formatMonitoringTextParam = (return formatNumber(param.count);case 'text':return translateLocalizedText(param.text, t);+ case 'moment':+ return formatMoment(param);}};++export const formatMoment = ({ at, isToday }: { at: string; isToday: boolean }): string =>+ dayjs(at).format(isToday ? getClockFormat() : getUserTimeFormat().format);diff --git a/frontend/src/features/backups/physical/monitoring/lib/pathStages.test.ts b/frontend/src/features/backups/physical/monitoring/lib/pathStages.test.tsindex 8fbfe81f..a5084b8d 100644--- a/frontend/src/features/backups/physical/monitoring/lib/pathStages.test.ts+++ b/frontend/src/features/backups/physical/monitoring/lib/pathStages.test.ts@@ -25,8 +25,18 @@ describe('getStageTones', () => {]);expect(stageTones[PathStage.DATABASUS]).toBe(MonitoringTone.WARNING);- expect(stageTones[PathStage.SOURCE]).toBe(MonitoringTone.SUCCESS);- expect(stageTones[PathStage.STORAGE]).toBe(MonitoringTone.SUCCESS);+ expect(stageTones[PathStage.SOURCE]).toBe(MonitoringTone.NEUTRAL);+ expect(stageTones[PathStage.STORAGE]).toBe(MonitoringTone.NEUTRAL);+ });++ it('leaves every stage neutral when the only reason is a broken chain', () => {+ const stageTones = getStageTones(WalStreamHealthLevel.BROKEN, [+ { code: WalStreamReasonCode.WAL_CHAIN_BROKEN, level: WalStreamReasonLevel.BROKEN },+ ]);++ expect(stageTones[PathStage.SOURCE]).toBe(MonitoringTone.NEUTRAL);+ expect(stageTones[PathStage.DATABASUS]).toBe(MonitoringTone.NEUTRAL);+ expect(stageTones[PathStage.STORAGE]).toBe(MonitoringTone.NEUTRAL);});it('takes the most severe reason of a stage', () => {@@ -38,6 +48,16 @@ describe('getStageTones', () => {expect(stageTones[PathStage.SOURCE]).toBe(MonitoringTone.ERROR);});+ it('leaves every stage neutral without a reason, so a healthy path draws no colored border', () => {+ const stageTones = getStageTones(WalStreamHealthLevel.HEALTHY, []);++ expect(Object.values(stageTones)).toEqual([+ MonitoringTone.NEUTRAL,+ MonitoringTone.NEUTRAL,+ MonitoringTone.NEUTRAL,+ ]);+ });+it('leaves every stage neutral while streaming is off', () => {const stageTones = getStageTones(WalStreamHealthLevel.NOT_STREAMING, []);diff --git a/frontend/src/features/backups/physical/monitoring/lib/pathStages.ts b/frontend/src/features/backups/physical/monitoring/lib/pathStages.tsindex 86fddd91..7b2d3f8f 100644--- a/frontend/src/features/backups/physical/monitoring/lib/pathStages.ts+++ b/frontend/src/features/backups/physical/monitoring/lib/pathStages.ts@@ -1,27 +1,44 @@import {WalStreamHealthLevel,type WalStreamReason,+ WalStreamReasonCode,WalStreamReasonLevel,} from '../../../../../entity/backups/physical';import type { AmountProgress } from '../model/AmountProgress';import { MonitoringTone } from '../model/MonitoringTone';import { PathStage } from '../model/PathStage';-import { REASON_STAGES } from './reasonTexts';-// Each stage takes the color of the most severe reason about it. Notices never color a stage, and-// without a verdict about streaming there is nothing to color.+// A broken chain is a hole in the backup history, not a problem of any stage the changes pass+// through, so it colors none.+const REASON_STAGES: Record<WalStreamReasonCode, PathStage | null> = {+ [WalStreamReasonCode.STREAMING_STOPPED]: PathStage.DATABASUS,+ [WalStreamReasonCode.SOURCE_UNREACHABLE]: PathStage.SOURCE,+ [WalStreamReasonCode.WAL_CHAIN_BROKEN]: null,+ [WalStreamReasonCode.SLOT_MISSING]: PathStage.SOURCE,+ [WalStreamReasonCode.SLOT_LOST]: PathStage.SOURCE,+ [WalStreamReasonCode.ARCHIVE_NOT_ADVANCING]: PathStage.STORAGE,+ [WalStreamReasonCode.ARCHIVE_SLOWER_THAN_SOURCE]: PathStage.STORAGE,+ [WalStreamReasonCode.SLOT_KEEPS_EXTRA_WAL]: PathStage.SOURCE,+ [WalStreamReasonCode.SLOT_LIMIT_APPROACHING]: PathStage.SOURCE,+ [WalStreamReasonCode.NEAR_SLOT_REBUILD]: PathStage.SOURCE,+ [WalStreamReasonCode.LOCAL_QUEUE_FILLING]: PathStage.DATABASUS,+ [WalStreamReasonCode.FREQUENT_RESTARTS]: PathStage.DATABASUS,+ [WalStreamReasonCode.FORCED_ROTATION_REFUSED]: PathStage.SOURCE,+};++// Each stage takes the color of the most severe reason about it, and stays neutral without one:+// a healthy color on every stage reads as a selection or an alarm. Notices never color a stage,+// and without a verdict about streaming there is nothing to color.export const getStageTones = (level: WalStreamHealthLevel,reasons: WalStreamReason[],): Record<PathStage, MonitoringTone> => {const isVerdictAboutStreaming =level !== WalStreamHealthLevel.NOT_STREAMING && level !== WalStreamHealthLevel.COLLECTING_DATA;- const defaultTone = isVerdictAboutStreaming ? MonitoringTone.SUCCESS : MonitoringTone.NEUTRAL;-const stageTones: Record<PathStage, MonitoringTone> = {- [PathStage.SOURCE]: defaultTone,- [PathStage.DATABASUS]: defaultTone,- [PathStage.STORAGE]: defaultTone,+ [PathStage.SOURCE]: MonitoringTone.NEUTRAL,+ [PathStage.DATABASUS]: MonitoringTone.NEUTRAL,+ [PathStage.STORAGE]: MonitoringTone.NEUTRAL,};if (!isVerdictAboutStreaming) {@@ -31,6 +48,10 @@ export const getStageTones = (for (const reason of reasons) {const stage = REASON_STAGES[reason.code];+ if (stage === null) {+ continue;+ }+if (reason.level === WalStreamReasonLevel.BROKEN) {stageTones[stage] = MonitoringTone.ERROR;} else if (diff --git a/frontend/src/features/backups/physical/monitoring/lib/reasonTexts.test.ts b/frontend/src/features/backups/physical/monitoring/lib/reasonTexts.test.tsindex 7591d250..e18fcd19 100644--- a/frontend/src/features/backups/physical/monitoring/lib/reasonTexts.test.ts+++ b/frontend/src/features/backups/physical/monitoring/lib/reasonTexts.test.ts@@ -7,7 +7,7 @@ import {WalStreamReasonLevel,} from '../../../../../entity/backups/physical';import { DICTIONARIES } from '../../../../../shared/i18n';-import { getNoticeTexts, getReasonTexts, sortReasonsBrokenFirst } from './reasonTexts';+import { getNoticeTexts, getReasonTexts, getTipTexts, sortReasonsBrokenFirst } from './reasonTexts';// The entity's public API imports its API client, and the client's config module reads window at// import time. The tests run in node, so they supply window.@@ -146,6 +146,19 @@ describe('sortReasonsBrokenFirst', () => {});});+describe('getTipTexts', () => {+ it('turns notices into tips, leaving the missing first full backup to the restore sentence', () => {+ const tips = getTipTexts([+ { code: WalStreamNoticeCode.NO_SLOT_WAL_LIMIT, level: WalStreamReasonLevel.INFO },+ { code: WalStreamNoticeCode.NO_FULL_BACKUP_YET, level: WalStreamReasonLevel.INFO },+ ]);++ expect(tips.map((tip) => tip.titleKey)).toEqual([+ 'backups.physical.monitoring.notices.noSlotWalLimit.title',+ ]);+ });+});+describe('the English monitoring copy', () => {// Technical names belong only where the reader asks for them: the collapsed details, the// explanations on hover, and a "what to do" sentence that names the setting to change.diff --git a/frontend/src/features/backups/physical/monitoring/lib/reasonTexts.ts b/frontend/src/features/backups/physical/monitoring/lib/reasonTexts.tsindex ca3a4e3a..b73ca2c3 100644--- a/frontend/src/features/backups/physical/monitoring/lib/reasonTexts.ts+++ b/frontend/src/features/backups/physical/monitoring/lib/reasonTexts.ts@@ -10,26 +10,9 @@ import {import type { TranslationKey } from '../../../../../shared/i18n';import type { MonitoringText } from '../model/MonitoringText';import type { MonitoringTextParam } from '../model/MonitoringTextParam';-import { PathStage } from '../model/PathStage';import type { ReasonTexts } from '../model/ReasonTexts';import { getRoundedDuration, getSecondsBetween } from './roundedDuration';-export const REASON_STAGES: Record<WalStreamReasonCode, PathStage> = {- [WalStreamReasonCode.STREAMING_STOPPED]: PathStage.DATABASUS,- [WalStreamReasonCode.SOURCE_UNREACHABLE]: PathStage.SOURCE,- [WalStreamReasonCode.WAL_CHAIN_BROKEN]: PathStage.STORAGE,- [WalStreamReasonCode.SLOT_MISSING]: PathStage.SOURCE,- [WalStreamReasonCode.SLOT_LOST]: PathStage.SOURCE,- [WalStreamReasonCode.ARCHIVE_NOT_ADVANCING]: PathStage.STORAGE,- [WalStreamReasonCode.ARCHIVE_SLOWER_THAN_SOURCE]: PathStage.STORAGE,- [WalStreamReasonCode.SLOT_KEEPS_EXTRA_WAL]: PathStage.SOURCE,- [WalStreamReasonCode.SLOT_LIMIT_APPROACHING]: PathStage.SOURCE,- [WalStreamReasonCode.NEAR_SLOT_REBUILD]: PathStage.SOURCE,- [WalStreamReasonCode.LOCAL_QUEUE_FILLING]: PathStage.DATABASUS,- [WalStreamReasonCode.FREQUENT_RESTARTS]: PathStage.DATABASUS,- [WalStreamReasonCode.FORCED_ROTATION_REFUSED]: PathStage.SOURCE,-};-interface ReasonSentenceKeys {whatHappened: TranslationKey;whatToDo: TranslationKey;@@ -111,12 +94,6 @@ const NOTICE_SENTENCE_KEYS: Record<WalStreamNoticeCode, ReasonSentenceKeys> = {},};-const NOTICE_STAGES: Record<WalStreamNoticeCode, PathStage> = {- [WalStreamNoticeCode.NO_SLOT_WAL_LIMIT]: PathStage.SOURCE,- [WalStreamNoticeCode.SLOT_KEEPS_EXTRA_WAL_STEADILY]: PathStage.SOURCE,- [WalStreamNoticeCode.NO_FULL_BACKUP_YET]: PathStage.STORAGE,-};-const REASON_LEVEL_ORDER: Record<WalStreamReasonLevel, number> = {[WalStreamReasonLevel.BROKEN]: 0,[WalStreamReasonLevel.NEEDS_ATTENTION]: 1,@@ -142,7 +119,6 @@ export const getReasonTexts = (return {level: reason.level,- stage: REASON_STAGES[reason.code],titleKey: WAL_STREAM_REASON_CODE_LABEL_KEYS[reason.code],whatHappened: { key: sentenceKeys.whatHappened, params: getReasonParams(reason, now) },whatToDo: { key: whatToDoKey },@@ -154,20 +130,26 @@ export const getNoticeTexts = (notice: WalStreamNotice): ReasonTexts => {return {level: notice.level,- stage: NOTICE_STAGES[notice.code],titleKey: WAL_STREAM_NOTICE_CODE_LABEL_KEYS[notice.code],whatHappened: { key: sentenceKeys.whatHappened },whatToDo: { key: sentenceKeys.whatToDo },};};+// The banner's restore sentence already says that no full backup has finished, so that notice is no+// tip.+export const getTipTexts = (notices: WalStreamNotice[]): ReasonTexts[] =>+ notices+ .filter((notice) => notice.code !== WalStreamNoticeCode.NO_FULL_BACKUP_YET)+ .map(getNoticeTexts);+const getReasonParams = (reason: WalStreamReason, now: Date): MonitoringText['params'] => {const params: Record<string, MonitoringTextParam> = {};if (reason.since !== undefined) {params.duration = {kind: 'text',- text: getRoundedDuration(getSecondsBetween(reason.since, now)),+ text: getRoundedDuration(getSecondsBetween(reason.since, now) ?? 0),};}diff --git a/frontend/src/features/backups/physical/monitoring/lib/restoreTimeline.test.ts b/frontend/src/features/backups/physical/monitoring/lib/restoreTimeline.test.tsnew file mode 100644index 00000000..82287f8f--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/lib/restoreTimeline.test.ts@@ -0,0 +1,154 @@+import { describe, expect, it, vi } from 'vitest';++import { RestoreTimelineSegmentKind } from '../model/RestoreTimelineSegmentKind';+import {+ MIN_SEGMENT_WIDTH_PERCENT,+ getLostStretchTexts,+ getRestoreTimeline,+} from './restoreTimeline';++// The entity's public API imports its API client, and the client's config module reads window at+// import time. The tests run in node, so they supply window.+vi.hoisted(() => {+ vi.stubGlobal('window', {});+});++const now = new Date('2026-10-20T12:00:00Z');+const at = (time: string) => new Date(time).getTime();++const getWidthTotal = (segments: { widthPercent: number }[]) =>+ segments.reduce((total, segment) => total + segment.widthPercent, 0);++describe('getRestoreTimeline', () => {+ it('draws nothing without a restorable range', () => {+ expect(getRestoreTimeline([], now)).toEqual([]);+ });++ it('fills the bar with one range that reaches now', () => {+ expect(+ getRestoreTimeline([{ from: '2026-10-20T08:00:00Z', to: '2026-10-20T12:00:00Z' }], now),+ ).toEqual([+ {+ kind: RestoreTimelineSegmentKind.RESTORABLE,+ fromMs: at('2026-10-20T08:00:00Z'),+ toMs: at('2026-10-20T12:00:00Z'),+ startPercent: 0,+ widthPercent: 100,+ },+ ]);+ });++ it('marks the stretch between two ranges as lost and the tail after the latest moment as not saved yet', () => {+ const segments = getRestoreTimeline(+ [+ { from: '2026-10-20T00:00:00Z', to: '2026-10-20T04:00:00Z' },+ { from: '2026-10-20T06:00:00Z', to: '2026-10-20T10:00:00Z' },+ ],+ now,+ );++ const expected: [RestoreTimelineSegmentKind, number, number][] = [+ [RestoreTimelineSegmentKind.RESTORABLE, 0, 4],+ [RestoreTimelineSegmentKind.LOST, 4, 2],+ [RestoreTimelineSegmentKind.RESTORABLE, 6, 4],+ [RestoreTimelineSegmentKind.NOT_SAVED_YET, 10, 2],+ ];++ expect(segments.map((segment) => segment.kind)).toEqual(expected.map(([kind]) => kind));+ expected.forEach(([, startHour, widthHours], index) => {+ expect(segments[index].startPercent).toBeCloseTo((startHour / 12) * 100);+ expect(segments[index].widthPercent).toBeCloseTo((widthHours / 12) * 100);+ });+ expect(segments[1]).toMatchObject({+ fromMs: at('2026-10-20T04:00:00Z'),+ toMs: at('2026-10-20T06:00:00Z'),+ });+ });++ it('keeps a lost hour visible on a chain three months long, and the bar still adds up to 100%', () => {+ const segments = getRestoreTimeline(+ [+ { from: '2026-07-20T12:00:00Z', to: '2026-09-01T12:00:00Z' },+ { from: '2026-09-01T13:00:00Z', to: '2026-10-20T12:00:00Z' },+ ],+ now,+ );++ expect(segments[1].kind).toBe(RestoreTimelineSegmentKind.LOST);+ expect(segments[1].widthPercent).toBe(MIN_SEGMENT_WIDTH_PERCENT);+ expect(getWidthTotal(segments)).toBeCloseTo(100);+ expect(segments[2].startPercent).toBeCloseTo(+ segments[0].widthPercent + MIN_SEGMENT_WIDTH_PERCENT,+ );+ });++ it('keeps a restorable single moment visible', () => {+ const segments = getRestoreTimeline(+ [+ { from: '2026-10-20T00:00:00Z', to: '2026-10-20T04:00:00Z' },+ { from: '2026-10-20T08:00:00Z', to: '2026-10-20T08:00:00Z' },+ ],+ new Date('2026-10-20T08:00:00Z'),+ );++ expect(segments[segments.length - 1]).toMatchObject({+ kind: RestoreTimelineSegmentKind.RESTORABLE,+ widthPercent: MIN_SEGMENT_WIDTH_PERCENT,+ });+ expect(getWidthTotal(segments)).toBeCloseTo(100);+ });++ it('does not stretch a short not saved yet tail', () => {+ const segments = getRestoreTimeline(+ [{ from: '2026-10-10T12:00:00Z', to: '2026-10-20T11:59:20Z' }],+ now,+ );++ expect(segments[1].kind).toBe(RestoreTimelineSegmentKind.NOT_SAVED_YET);+ expect(segments[1].widthPercent).toBeLessThan(MIN_SEGMENT_WIDTH_PERCENT);+ });+});++describe('getLostStretchTexts', () => {+ const buildRanges = (lostCount: number) =>+ Array.from({ length: lostCount + 1 }, (_, index) => ({+ from: new Date(Date.parse('2026-10-20T00:00:00Z') + index * 2 * 3600_000).toISOString(),+ to: new Date(Date.parse('2026-10-20T01:00:00Z') + index * 2 * 3600_000).toISOString(),+ }));++ it('says nothing without a lost stretch', () => {+ expect(getLostStretchTexts(getRestoreTimeline(buildRanges(0), now), now)).toEqual([]);+ });++ it('names the start and end of a lost stretch, as a time of day for today and with a date before', () => {+ const segments = getRestoreTimeline(+ [+ { from: '2026-10-10T12:00:00Z', to: '2026-10-10T15:35:00Z' },+ { from: '2026-10-20T04:51:00Z', to: '2026-10-20T11:59:00Z' },+ ],+ now,+ );++ expect(getLostStretchTexts(segments, now)).toEqual([+ {+ key: 'backups.physical.monitoring.restoreTimeline.lostSentence',+ params: {+ from: { kind: 'moment', at: '2026-10-10T15:35:00.000Z', isToday: false },+ to: { kind: 'moment', at: '2026-10-20T04:51:00.000Z', isToday: true },+ },+ },+ ]);+ });++ it('lists three lost stretches and counts the rest', () => {+ const texts = getLostStretchTexts(getRestoreTimeline(buildRanges(5), now), now);++ expect(texts.map((text) => text.key)).toEqual([+ 'backups.physical.monitoring.restoreTimeline.lostSentence',+ 'backups.physical.monitoring.restoreTimeline.lostSentence',+ 'backups.physical.monitoring.restoreTimeline.lostSentence',+ 'backups.physical.monitoring.restoreTimeline.moreLost',+ ]);+ expect(texts[3].params).toEqual({ count: { kind: 'count', count: 2 } });+ });+});diff --git a/frontend/src/features/backups/physical/monitoring/lib/restoreTimeline.ts b/frontend/src/features/backups/physical/monitoring/lib/restoreTimeline.tsnew file mode 100644index 00000000..e632b089--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/lib/restoreTimeline.ts@@ -0,0 +1,163 @@+import dayjs from 'dayjs';++import type { WalStreamTimeRange } from '../../../../../entity/backups/physical';+import type { MonitoringText } from '../model/MonitoringText';+import type { MonitoringTextParam } from '../model/MonitoringTextParam';+import type { RestoreTimelineSegment } from '../model/RestoreTimelineSegment';+import { RestoreTimelineSegmentKind } from '../model/RestoreTimelineSegmentKind';++// A lost stretch of a few hours on a chain months long would be thinner than a pixel, so every+// stretch except the not saved yet tail keeps this share of the bar.+export const MIN_SEGMENT_WIDTH_PERCENT = 1.5;++// Past three sentences the list stops helping, so the rest is only counted.+const MAX_LOST_SENTENCES = 3;++interface TimelineStretch {+ kind: RestoreTimelineSegmentKind;+ fromMs: number;+ toMs: number;+}++// The bar runs from the start of the first restorable range to now: the ranges, the lost+// stretches between them, and the tail after the latest restorable moment that is not saved yet.+export const getRestoreTimeline = (+ ranges: WalStreamTimeRange[],+ now: Date,+): RestoreTimelineSegment[] => {+ const stretches = getStretches(ranges, now.getTime());++ if (stretches.length === 0) {+ return [];+ }++ const startMs = stretches[0].fromMs;+ const totalMs = stretches[stretches.length - 1].toMs - startMs;++ if (totalMs <= 0) {+ return stretches.map((stretch, index) => ({+ ...stretch,+ startPercent: 0,+ widthPercent: index === 0 ? 100 : 0,+ }));+ }++ const widths = getWidthsWithMinimum(+ stretches.map((stretch) => ((stretch.toMs - stretch.fromMs) / totalMs) * 100),+ stretches.map((stretch) => stretch.kind !== RestoreTimelineSegmentKind.NOT_SAVED_YET),+ );++ let startPercent = 0;++ return stretches.map((stretch, index) => {+ const segment = { ...stretch, startPercent, widthPercent: widths[index] };+ startPercent += widths[index];++ return segment;+ });+};++const getStretches = (ranges: WalStreamTimeRange[], nowMs: number): TimelineStretch[] => {+ const stretches: TimelineStretch[] = [];++ ranges.forEach((range, index) => {+ const fromMs = new Date(range.from).getTime();+ const toMs = new Date(range.to).getTime();++ stretches.push({ kind: RestoreTimelineSegmentKind.RESTORABLE, fromMs, toMs });++ const nextRange = ranges[index + 1];++ if (nextRange) {+ stretches.push({+ kind: RestoreTimelineSegmentKind.LOST,+ fromMs: toMs,+ toMs: new Date(nextRange.from).getTime(),+ });+ }+ });++ const lastStretch = stretches[stretches.length - 1] as TimelineStretch | undefined;++ if (lastStretch && nowMs > lastStretch.toMs) {+ stretches.push({+ kind: RestoreTimelineSegmentKind.NOT_SAVED_YET,+ fromMs: lastStretch.toMs,+ toMs: nowMs,+ });+ }++ return stretches;+};++// Raises the widths that may not shrink below the minimum and takes the difference from the+// others in proportion, so the bar still adds up to 100%.+const getWidthsWithMinimum = (widths: number[], isMinimumApplied: boolean[]): number[] => {+ const isRaised = widths.map(+ (width, index) => isMinimumApplied[index] && width < MIN_SEGMENT_WIDTH_PERCENT,+ );+ const raisedTotal = isRaised.filter(Boolean).length * MIN_SEGMENT_WIDTH_PERCENT;+ const otherTotal = widths.reduce(+ (total, width, index) => total + (isRaised[index] ? 0 : width),+ 0,+ );++ if (raisedTotal === 0 || otherTotal === 0) {+ return widths;+ }++ const scale = (100 - raisedTotal) / otherTotal;++ return widths.map((width, index) =>+ isRaised[index] ? MIN_SEGMENT_WIDTH_PERCENT : width * scale,+ );+};++// The text under the bar, so the lost stretches are said in words and not by color alone.+export const getLostStretchTexts = (+ segments: RestoreTimelineSegment[],+ now: Date,+): MonitoringText[] => {+ const lostSegments = segments.filter(+ (segment) => segment.kind === RestoreTimelineSegmentKind.LOST,+ );++ const texts: MonitoringText[] = lostSegments.slice(0, MAX_LOST_SENTENCES).map((segment) => ({+ key: 'backups.physical.monitoring.restoreTimeline.lostSentence',+ params: getRangeParams(segment, now),+ }));++ if (lostSegments.length > MAX_LOST_SENTENCES) {+ texts.push({+ key: 'backups.physical.monitoring.restoreTimeline.moreLost',+ params: { count: { kind: 'count', count: lostSegments.length - MAX_LOST_SENTENCES } },+ });+ }++ return texts;+};++export const getSegmentRangeText = (+ segment: RestoreTimelineSegment,+ now: Date,+): MonitoringText => ({+ key: 'backups.physical.monitoring.restoreTimeline.range',+ params: getRangeParams(segment, now),+});++export const getMomentParam = (+ atMs: number,+ now: Date,+): Extract<MonitoringTextParam, { kind: 'moment' }> => ({+ kind: 'moment',+ at: new Date(atMs).toISOString(),+ isToday: dayjs(atMs).isSame(now, 'day'),+});++const getRangeParams = (+ segment: RestoreTimelineSegment,+ now: Date,+): Record<string, MonitoringTextParam> => ({+ from: getMomentParam(segment.fromMs, now),+ to: getMomentParam(segment.toMs, now),+});diff --git a/frontend/src/features/backups/physical/monitoring/lib/roundedDuration.test.ts b/frontend/src/features/backups/physical/monitoring/lib/roundedDuration.test.tsindex 3201054a..e333ae3c 100644--- a/frontend/src/features/backups/physical/monitoring/lib/roundedDuration.test.ts+++ b/frontend/src/features/backups/physical/monitoring/lib/roundedDuration.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { getMeasurementAge, getRoundedDuration } from './roundedDuration';+import { getMeasurementAge, getRoundedDuration, getSecondsBetween } from './roundedDuration';describe('getRoundedDuration', () => {it.each([@@ -28,6 +28,29 @@ describe('getRoundedDuration', () => {});});+describe('getSecondsBetween', () => {+ const now = new Date('2026-10-18T12:00:00Z');++ it('counts the seconds from an earlier time', () => {+ expect(getSecondsBetween('2026-10-18T11:59:20Z', now)).toBe(40);+ });++ it('never goes below zero for a time slightly in the future', () => {+ expect(getSecondsBetween('2026-10-18T12:00:05Z', now)).toBe(0);+ });++ it.each([['not a time'], [''], [undefined as unknown as string]])(+ 'is null for a time it cannot read (%j), so no "NaN" reaches the screen',+ (earlier) => {+ expect(getSecondsBetween(earlier, now)).toBeNull();+ },+ );++ it('is null when now itself is invalid', () => {+ expect(getSecondsBetween('2026-10-18T11:59:20Z', new Date(Number.NaN))).toBeNull();+ });+});+describe('getMeasurementAge', () => {it('counts seconds under a minute', () => {expect(getMeasurementAge(12.7)).toEqual({diff --git a/frontend/src/features/backups/physical/monitoring/lib/roundedDuration.ts b/frontend/src/features/backups/physical/monitoring/lib/roundedDuration.tsindex e24b01b6..46edb78a 100644--- a/frontend/src/features/backups/physical/monitoring/lib/roundedDuration.ts+++ b/frontend/src/features/backups/physical/monitoring/lib/roundedDuration.ts@@ -49,5 +49,15 @@ export const getMeasurementAge = (seconds: number): LocalizedText => {return getRoundedDuration(seconds);};-export const getSecondsBetween = (earlier: string | Date, later: Date): number =>- Math.max(0, (later.getTime() - new Date(earlier).getTime()) / 1000);+// Null when either time cannot be read, so a caller leaves the duration out instead of showing+// "NaN d NaN h".+export const getSecondsBetween = (earlier: string | Date, later: Date): number | null => {+ const earlierMs = new Date(earlier).getTime();+ const laterMs = later.getTime();++ if (!Number.isFinite(earlierMs) || !Number.isFinite(laterMs)) {+ return null;+ }++ return Math.max(0, (laterMs - earlierMs) / 1000);+};diff --git a/frontend/src/features/backups/physical/monitoring/lib/testPageVisibility.ts b/frontend/src/features/backups/physical/monitoring/lib/testPageVisibility.tsnew file mode 100644index 00000000..9774294e--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/lib/testPageVisibility.ts@@ -0,0 +1,22 @@+import type { PageVisibility } from './walStreamRefreshController';++// Page visibility the tests switch by hand, telling subscribers as the browser would.+export class FakePageVisibility implements PageVisibility {+ private isPageVisible = true;+ private listeners: (() => void)[] = [];++ isVisible = () => this.isPageVisible;++ subscribe = (onVisibilityChange: () => void) => {+ this.listeners.push(onVisibilityChange);++ return () => {+ this.listeners = this.listeners.filter((listener) => listener !== onVisibilityChange);+ };+ };++ setVisible(isPageVisible: boolean) {+ this.isPageVisible = isPageVisible;+ this.listeners.forEach((listener) => listener());+ }+}diff --git a/frontend/src/features/backups/physical/monitoring/lib/testWalStreamStatistics.ts b/frontend/src/features/backups/physical/monitoring/lib/testWalStreamStatistics.tsnew file mode 100644index 00000000..3bb5f20e--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/lib/testWalStreamStatistics.ts@@ -0,0 +1,82 @@+/* eslint-disable i18next/no-literal-string -- a test fixture of UTC times and WAL positions, not copy */+import {+ WalStreamHealthLevel,+ WalStreamKeepingUpState,+ WalStreamSourceState,+ type WalStreamStatistics,+ WalStreamStatisticsPeriod,+ WalStreamStreamerState,+} from '../../../../../entity/backups/physical';++const MiB = 1024 * 1024;++// Statistics of a healthy database at 12:00 UTC on 2026-10-18, for the slice's tests to adjust+// field by field.+export const createTestWalStreamStatistics = (+ overrides: Partial<WalStreamStatistics> = {},+): WalStreamStatistics => ({+ health: {+ level: WalStreamHealthLevel.HEALTHY,+ reasons: [],+ notices: [],+ isFullBackupPending: false,+ },+ latestRestorableAt: '2026-10-18T11:59:20Z',+ restorableRanges: [{ from: '2026-10-17T03:00:00Z', to: '2026-10-18T11:59:20Z' }],+ streamer: {+ state: WalStreamStreamerState.RUNNING,+ sessionStartedAt: '2026-10-18T10:00:00Z',+ failingSince: null,+ restartsLastHour: 0,+ },+ current: {+ sampledAt: '2026-10-18T11:59:48Z',+ lastArchivedWalAt: '2026-10-18T11:59:20Z',+ sessionStartedAt: '2026-10-18T10:00:00Z',+ sourceState: WalStreamSourceState.REACHABLE,+ sourceUnreachableSince: null,+ sourceCurrentLsn: '0/5000000',+ archiveProgressLsn: '0/4F00000',+ sourceWrittenBytes: 16 * MiB,+ archivedSegments: 2,+ archivedWalBytes: 32 * MiB,+ archivedStoredBytes: 8 * MiB,+ walSegmentSizeBytes: 16 * MiB,+ highestConcurrentUploads: 3,+ segmentWriteAvgMillis: 120,+ segmentWriteMaxMillis: 300,+ slotWalStatus: 'reserved',+ slotExtraWalSince: null,+ slotLagBytes: 2 * MiB,+ slotSafeWalSizeBytes: null,+ unarchivedWalBytes: 20 * MiB,+ archiveStalledSince: null,+ localQueueBytes: 0,+ localQueuePauseBytes: 512 * MiB,+ receiverRestarts: 0,+ receiverPauses: 0,+ isReceiverRunning: true,+ isForcedRotationDenied: false,+ },+ keepingUp: {+ state: WalStreamKeepingUpState.KEEPING_UP,+ sourceWriteBytesPerSecond: 10 * MiB,+ archiveBytesPerSecond: 10 * MiB,+ unarchivedWalBytes: 20 * MiB,+ unarchivedWalChangeBytesPerSecond: 0,+ slotLagBytes: 2 * MiB,+ slotLagChangeBytesPerSecond: 0,+ slotRebuildLagBytes: 256 * MiB,+ estimatedCatchUpSeconds: null,+ estimatedSlotRebuildSeconds: null,+ estimatedSlotLimitSeconds: null,+ },+ series: {+ period: WalStreamStatisticsPeriod.HOUR,+ bucketSeconds: 60,+ from: '2026-10-18T11:01:00Z',+ to: '2026-10-18T12:01:00Z',+ points: [],+ },+ ...overrides,+});diff --git a/frontend/src/features/backups/physical/monitoring/lib/verdictBanner.test.ts b/frontend/src/features/backups/physical/monitoring/lib/verdictBanner.test.tsindex cf15c1e5..98c253c8 100644--- a/frontend/src/features/backups/physical/monitoring/lib/verdictBanner.test.ts+++ b/frontend/src/features/backups/physical/monitoring/lib/verdictBanner.test.ts@@ -1,69 +1,227 @@import { describe, expect, it, vi } from 'vitest';-import { WalStreamHealthLevel } from '../../../../../entity/backups/physical';+import {+ type WalStreamHealth,+ WalStreamHealthLevel,+ WalStreamReasonCode,+ WalStreamReasonLevel,+} from '../../../../../entity/backups/physical';import { MonitoringTone } from '../model/MonitoringTone';import { VerdictIcon } from '../model/VerdictIcon';+import { createTestWalStreamStatistics } from './testWalStreamStatistics';import { getVerdictBanner } from './verdictBanner';// The entity's public API imports its API client, and the client's config module reads window at-// import time. The tests run in node, so they supply window.+// import time. The tests run in node, so they supply window. Whether a moment is from today depends+// on the time zone, so the tests pin it.vi.hoisted(() => {vi.stubGlobal('window', {});+ vi.stubEnv('TZ', 'UTC');});const now = new Date('2026-10-18T12:00:00Z');+const getBannerFor = (+ health: Partial<WalStreamHealth>,+ overrides: Parameters<typeof createTestWalStreamStatistics>[0] = {},+ lastSuccessfulRefreshAt = now,+) => {+ const statistics = createTestWalStreamStatistics(overrides);++ return getVerdictBanner({+ statistics: { ...statistics, health: { ...statistics.health, ...health } },+ lastSuccessfulRefreshAt,+ now,+ });+};++const brokenChainReason = {+ code: WalStreamReasonCode.WAL_CHAIN_BROKEN,+ level: WalStreamReasonLevel.BROKEN,+};+describe('getVerdictBanner', () => {it.each([- [- WalStreamHealthLevel.HEALTHY,- MonitoringTone.SUCCESS,- VerdictIcon.CHECK,- 'backups.physical.monitoring.levels.healthy',- ],- [- WalStreamHealthLevel.NEEDS_ATTENTION,- MonitoringTone.WARNING,- VerdictIcon.EXCLAMATION,- 'backups.physical.monitoring.levels.needsAttention',- ],- [- WalStreamHealthLevel.BROKEN,- MonitoringTone.ERROR,- VerdictIcon.CLOSE,- 'backups.physical.monitoring.levels.broken',- ],- [- WalStreamHealthLevel.COLLECTING_DATA,- MonitoringTone.NEUTRAL,- VerdictIcon.CLOCK,- 'backups.physical.monitoring.levels.collectingData',- ],- [- WalStreamHealthLevel.NOT_STREAMING,- MonitoringTone.NEUTRAL,- VerdictIcon.PAUSE,- 'backups.physical.monitoring.levels.notStreaming',- ],- ])('shows %s with its own color, icon and headline', (level, tone, icon, headlineKey) => {- const banner = getVerdictBanner(level, now, now);+ [WalStreamHealthLevel.HEALTHY, MonitoringTone.SUCCESS, VerdictIcon.CHECK],+ [WalStreamHealthLevel.NEEDS_ATTENTION, MonitoringTone.WARNING, VerdictIcon.EXCLAMATION],+ [WalStreamHealthLevel.BROKEN, MonitoringTone.ERROR, VerdictIcon.CLOSE],+ [WalStreamHealthLevel.COLLECTING_DATA, MonitoringTone.NEUTRAL, VerdictIcon.CLOCK],+ [WalStreamHealthLevel.NOT_STREAMING, MonitoringTone.NEUTRAL, VerdictIcon.PAUSE],+ ])('shows %s with its own color and icon', (level, tone, icon) => {+ const banner = getBannerFor({ level });expect(banner.tone).toBe(tone);expect(banner.icon).toBe(icon);- expect(banner.headlineKey).toBe(headlineKey);+ });++ it('says that all changes are being saved when healthy', () => {+ const banner = getBannerFor({ level: WalStreamHealthLevel.HEALTHY });++ expect(banner.headlineKey).toBe('backups.physical.monitoring.banner.healthyHeadline');+ expect(banner.headlineReason).toBeUndefined();+ expect(banner.otherReasons).toEqual([]);+ });++ it('names the problem in the headline instead of the verdict', () => {+ const banner = getBannerFor({+ level: WalStreamHealthLevel.BROKEN,+ reasons: [brokenChainReason],+ });++ expect(banner.headlineKey).toBe('backups.physical.monitoring.reasons.walChainBroken.title');+ expect(banner.headlineReason?.whatHappened.key).toBe(+ 'backups.physical.monitoring.reasons.walChainBroken.whatHappened',+ );+ expect(banner.headlineReason?.whatToDo.key).toBe(+ 'backups.physical.monitoring.reasons.walChainBroken.whatToDo',+ );+ });++ it('heads with a broken reason and lists needs-attention ones after it', () => {+ const banner = getBannerFor({+ level: WalStreamHealthLevel.BROKEN,+ reasons: [+ {+ code: WalStreamReasonCode.LOCAL_QUEUE_FILLING,+ level: WalStreamReasonLevel.NEEDS_ATTENTION,+ },+ { code: WalStreamReasonCode.SLOT_MISSING, level: WalStreamReasonLevel.BROKEN },+ ],+ });++ expect(banner.headlineKey).toBe('backups.physical.monitoring.reasons.slotMissing.title');+ expect(banner.otherReasons.map((reason) => reason.titleKey)).toEqual([+ 'backups.physical.monitoring.reasons.localQueueFilling.title',+ ]);+ });++ it.each([+ [WalStreamHealthLevel.COLLECTING_DATA, 'backups.physical.monitoring.levels.collectingData'],+ [WalStreamHealthLevel.NOT_STREAMING, 'backups.physical.monitoring.levels.notStreaming'],+ ])('keeps the headline of %s', (level, headlineKey) => {+ expect(getBannerFor({ level }).headlineKey).toBe(headlineKey);});it('links the not streaming headline to the configuration', () => {- expect(getVerdictBanner(WalStreamHealthLevel.NOT_STREAMING, now, now).isConfigLinkShown).toBe(+ expect(getBannerFor({ level: WalStreamHealthLevel.NOT_STREAMING }).isConfigLinkShown).toBe(true,);- expect(getVerdictBanner(WalStreamHealthLevel.HEALTHY, now, now).isConfigLinkShown).toBe(false);+ expect(getBannerFor({ level: WalStreamHealthLevel.HEALTHY }).isConfigLinkShown).toBe(false);});- it('cannot confirm the state when refreshes have failed for 3 minutes after a healthy response', () => {+ it('says to which time today the database can be restored, and how long ago that was', () => {+ const banner = getBannerFor({}, { latestRestorableAt: '2026-10-18T11:59:30Z' });++ expect(banner.restoreSentence).toEqual({+ key: 'backups.physical.monitoring.banner.restoreUpTo',+ params: {+ moment: { kind: 'moment', at: '2026-10-18T11:59:30Z', isToday: true },+ age: {+ kind: 'text',+ text: { key: 'backups.physical.monitoring.durations.seconds', params: { seconds: 30 } },+ },+ },+ });+ });++ it('shows a restorable moment from an earlier day with its date', () => {+ const banner = getBannerFor({}, { latestRestorableAt: '2026-10-17T22:00:00Z' });++ expect(banner.restoreSentence.params?.moment).toEqual({+ kind: 'moment',+ at: '2026-10-17T22:00:00Z',+ isToday: false,+ });+ });++ it('says that only an earlier moment can be restored while saved changes lie beyond a broken chain', () => {+ const statistics = createTestWalStreamStatistics();+ const banner = getBannerFor(+ { level: WalStreamHealthLevel.BROKEN, reasons: [brokenChainReason] },+ {+ latestRestorableAt: '2026-10-18T07:50:00Z',+ current: statistics.current && {+ ...statistics.current,+ lastArchivedWalAt: '2026-10-18T07:58:00Z',+ },+ },+ );++ expect(banner.restoreSentence.key).toBe('backups.physical.monitoring.banner.restoreOnlyUpTo');+ });++ it('names where the newest restorable stretch starts when an earlier stretch cannot be restored', () => {+ const banner = getBannerFor(+ {},+ {+ latestRestorableAt: '2026-10-18T11:59:30Z',+ restorableRanges: [+ { from: '2026-10-10T14:51:00Z', to: '2026-10-10T15:35:00Z' },+ { from: '2026-10-17T04:51:00Z', to: '2026-10-18T11:59:30Z' },+ ],+ },+ );++ expect(banner.restoreSentence.key).toBe('backups.physical.monitoring.banner.restoreFromUpTo');+ expect(banner.restoreSentence.params?.from).toEqual({+ kind: 'moment',+ at: '2026-10-17T04:51:00Z',+ isToday: false,+ });+ });++ it('says "any moment up to" without a start while one stretch covers the whole history', () => {+ const banner = getBannerFor({}, { latestRestorableAt: '2026-10-18T11:59:30Z' });++ expect(banner.restoreSentence.params).not.toHaveProperty('from');+ });++ it.each([+ [[], 'backups.physical.monitoring.banner.restoreUpToWithoutAge'],+ [[brokenChainReason], 'backups.physical.monitoring.banner.restoreOnlyUpToWithoutAge'],+ ])(+ 'leaves the age out instead of showing NaN when the moment cannot be read (%#)',+ (reasons, restoreKey) => {+ const banner = getBannerFor(+ {+ level: reasons.length ? WalStreamHealthLevel.BROKEN : WalStreamHealthLevel.HEALTHY,+ reasons,+ },+ { latestRestorableAt: 'not a time' },+ );++ expect(banner.restoreSentence.key).toBe(restoreKey);+ expect(banner.restoreSentence.params).not.toHaveProperty('age');+ },+ );++ it.each([+ [false, 'backups.physical.monitoring.banner.restoreNothing'],+ [true, 'backups.physical.monitoring.banner.restoreNothingPending'],+ ])(+ 'says that nothing can be restored before the first full backup (pending: %s)',+ (isFullBackupPending, restoreKey) => {+ const banner = getBannerFor({ isFullBackupPending }, { latestRestorableAt: null });++ expect(banner.restoreSentence).toEqual({ key: restoreKey });+ },+ );++ it('says that nothing can be restored yet while a just-enabled database collects data', () => {+ const banner = getBannerFor(+ { level: WalStreamHealthLevel.COLLECTING_DATA },+ { latestRestorableAt: null },+ );++ expect(banner.restoreSentence).toEqual({+ key: 'backups.physical.monitoring.banner.restoreNothing',+ });+ });++ it('cannot confirm the state when refreshes have failed for 3 minutes, and keeps the last known restorable moment', () => {const lastSuccessfulRefreshAt = new Date(now.getTime() - 3 * 60 * 1000);- const banner = getVerdictBanner(WalStreamHealthLevel.HEALTHY, lastSuccessfulRefreshAt, now);+ const banner = getBannerFor({}, {}, lastSuccessfulRefreshAt);expect(banner.isStateConfirmed).toBe(false);expect(banner.tone).toBe(MonitoringTone.NEUTRAL);@@ -79,13 +237,12 @@ describe('getVerdictBanner', () => {},},});+ expect(banner.restoreSentence.key).toBe('backups.physical.monitoring.banner.restoreUpTo');});it('keeps the verdict while the last refresh is under 2 minutes old', () => {const lastSuccessfulRefreshAt = new Date(now.getTime() - 90 * 1000);- expect(getVerdictBanner(WalStreamHealthLevel.HEALTHY, lastSuccessfulRefreshAt, now).tone).toBe(- MonitoringTone.SUCCESS,- );+ expect(getBannerFor({}, {}, lastSuccessfulRefreshAt).tone).toBe(MonitoringTone.SUCCESS);});});diff --git a/frontend/src/features/backups/physical/monitoring/lib/verdictBanner.ts b/frontend/src/features/backups/physical/monitoring/lib/verdictBanner.tsindex 474b08f9..70bd69e8 100644--- a/frontend/src/features/backups/physical/monitoring/lib/verdictBanner.ts+++ b/frontend/src/features/backups/physical/monitoring/lib/verdictBanner.ts@@ -1,16 +1,29 @@+import dayjs from 'dayjs';+import {WAL_STREAM_HEALTH_LEVEL_LABEL_KEYS,WalStreamHealthLevel,+ WalStreamReasonCode,+ type WalStreamStatistics,} from '../../../../../entity/backups/physical';+import type { MonitoringText } from '../model/MonitoringText';+import type { MonitoringTextParam } from '../model/MonitoringTextParam';import { MonitoringTone } from '../model/MonitoringTone';import type { VerdictBanner } from '../model/VerdictBanner';import { VerdictIcon } from '../model/VerdictIcon';-import { getRoundedDuration, getSecondsBetween } from './roundedDuration';+import { getReasonTexts, sortReasonsBrokenFirst } from './reasonTexts';+import { getMeasurementAge, getRoundedDuration, getSecondsBetween } from './roundedDuration';// Four missed refreshes: past this the screen no longer knows the current state, and showing the// last verdict in its own color would claim otherwise.export const UNCONFIRMED_STATE_AFTER_MS = 2 * 60 * 1000;+interface VerdictBannerInput {+ statistics: WalStreamStatistics;+ lastSuccessfulRefreshAt: Date;+ now: Date;+}+const LEVEL_TONES: Record<WalStreamHealthLevel, MonitoringTone> = {[WalStreamHealthLevel.HEALTHY]: MonitoringTone.SUCCESS,[WalStreamHealthLevel.NEEDS_ATTENTION]: MonitoringTone.WARNING,@@ -27,11 +40,14 @@ const LEVEL_ICONS: Record<WalStreamHealthLevel, VerdictIcon> = {[WalStreamHealthLevel.NOT_STREAMING]: VerdictIcon.PAUSE,};-export const getVerdictBanner = (- level: WalStreamHealthLevel,- lastSuccessfulRefreshAt: Date,- now: Date,-): VerdictBanner => {+export const getVerdictBanner = ({+ statistics,+ lastSuccessfulRefreshAt,+ now,+}: VerdictBannerInput): VerdictBanner => {+ const { level } = statistics.health;+ const restoreSentence = getRestoreSentence(statistics, now);+if (now.getTime() - lastSuccessfulRefreshAt.getTime() > UNCONFIRMED_STATE_AFTER_MS) {return {tone: MonitoringTone.NEUTRAL,@@ -43,32 +59,125 @@ export const getVerdictBanner = (level: { kind: 'text', text: { key: WAL_STREAM_HEALTH_LEVEL_LABEL_KEYS[level] } },duration: {kind: 'text',- text: getRoundedDuration(getSecondsBetween(lastSuccessfulRefreshAt, now)),+ text: getRoundedDuration(getSecondsBetween(lastSuccessfulRefreshAt, now) ?? 0),},},},+ otherReasons: [],+ restoreSentence,isConfigLinkShown: false,isStateConfirmed: false,};}- return {+ const banner: VerdictBanner = {tone: LEVEL_TONES[level],icon: LEVEL_ICONS[level],headlineKey: WAL_STREAM_HEALTH_LEVEL_LABEL_KEYS[level],- description: getLevelDescription(level),+ otherReasons: [],+ restoreSentence,isConfigLinkShown: level === WalStreamHealthLevel.NOT_STREAMING,isStateConfirmed: true,};-};-const getLevelDescription = (level: WalStreamHealthLevel): VerdictBanner['description'] => {switch (level) {+ case WalStreamHealthLevel.HEALTHY:+ return { ...banner, headlineKey: 'backups.physical.monitoring.banner.healthyHeadline' };+case WalStreamHealthLevel.COLLECTING_DATA:- return { key: 'backups.physical.monitoring.banner.collectingDataDescription' };+ return {+ ...banner,+ description: { key: 'backups.physical.monitoring.banner.collectingDataDescription' },+ };+case WalStreamHealthLevel.NOT_STREAMING:- return { key: 'backups.physical.monitoring.banner.notStreamingDescription' };+ return {+ ...banner,+ description: { key: 'backups.physical.monitoring.banner.notStreamingDescription' },+ };+default:- return undefined;+ return withReasons(banner, statistics, now);+ }+};++const withReasons = (+ banner: VerdictBanner,+ statistics: WalStreamStatistics,+ now: Date,+): VerdictBanner => {+ const [headlineReason, ...otherReasons] = sortReasonsBrokenFirst(statistics.health.reasons).map(+ (reason) => getReasonTexts(reason, statistics.health.isFullBackupPending, now),+ );++ if (!headlineReason) {+ return banner;+ }++ return { ...banner, headlineKey: headlineReason.titleKey, headlineReason, otherReasons };+};++const getRestoreSentence = (statistics: WalStreamStatistics, now: Date): MonitoringText => {+ const { latestRestorableAt, health } = statistics;++ if (latestRestorableAt === null) {+ return {+ key: health.isFullBackupPending+ ? 'backups.physical.monitoring.banner.restoreNothingPending'+ : 'backups.physical.monitoring.banner.restoreNothing',+ };+ }++ const moment = toMomentParam(latestRestorableAt, now);+ const ageSeconds = getSecondsBetween(latestRestorableAt, now);+ // The backend lists the broken chain reason only for a gap the latest restore cannot cross, so+ // the reason alone means saved changes lie beyond the restorable moment.+ const isLimitedByBrokenChain = health.reasons.some(+ (reason) => reason.code === WalStreamReasonCode.WAL_CHAIN_BROKEN,+ );+ // With a stretch that cannot be restored, "any moment up to" would promise the moments of that+ // stretch too, so the sentence names where the newest restorable stretch starts.+ const newestRange = statistics.restorableRanges[statistics.restorableRanges.length - 1];+ const from =+ !isLimitedByBrokenChain && statistics.restorableRanges.length > 1 && newestRange+ ? toMomentParam(newestRange.from, now)+ : null;++ if (ageSeconds === null) {+ if (from) {+ return {+ key: 'backups.physical.monitoring.banner.restoreFromUpToWithoutAge',+ params: { from, moment },+ };+ }++ return {+ key: isLimitedByBrokenChain+ ? 'backups.physical.monitoring.banner.restoreOnlyUpToWithoutAge'+ : 'backups.physical.monitoring.banner.restoreUpToWithoutAge',+ params: { moment },+ };}++ const age: MonitoringTextParam = { kind: 'text', text: getMeasurementAge(ageSeconds) };++ if (from) {+ return {+ key: 'backups.physical.monitoring.banner.restoreFromUpTo',+ params: { from, moment, age },+ };+ }++ return {+ key: isLimitedByBrokenChain+ ? 'backups.physical.monitoring.banner.restoreOnlyUpTo'+ : 'backups.physical.monitoring.banner.restoreUpTo',+ params: { moment, age },+ };};++const toMomentParam = (at: string, now: Date): MonitoringTextParam => ({+ kind: 'moment',+ at,+ isToday: dayjs(at).isSame(now, 'day'),+});diff --git a/frontend/src/features/backups/physical/monitoring/lib/walStreamLiveController.test.ts b/frontend/src/features/backups/physical/monitoring/lib/walStreamLiveController.test.tsnew file mode 100644index 00000000..c0d47016--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/lib/walStreamLiveController.test.ts@@ -0,0 +1,153 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { WalStreamLive, WalStreamLiveResponse } from '../../../../../entity/backups/physical';+import { FakePageVisibility } from './testPageVisibility';+import { WAL_STREAM_LIVE_INTERVAL_MS, WalStreamLiveController } from './walStreamLiveController';++// The entity's public API imports its API client, and the client's config module reads window at+// import time. The tests run in node, so they supply window.+vi.hoisted(() => {+ vi.stubGlobal('window', {});+});++const buildLive = (localQueueBytes: number): WalStreamLive =>+ ({ measuredAt: '2026-10-18T12:00:00Z', localQueueBytes }) as WalStreamLive;++const runningResponse = (localQueueBytes: number): WalStreamLiveResponse => ({+ isStreamerRunning: true,+ current: buildLive(localQueueBytes),+});++const createHarness = (fetchLive: () => Promise<WalStreamLiveResponse>) => {+ const pageVisibility = new FakePageVisibility();+ const onLiveChange = vi.fn();+ const fetchLiveMock = vi.fn(fetchLive);++ const controller = new WalStreamLiveController(+ {+ fetchLive: fetchLiveMock,+ timer: {+ setInterval: (callback, intervalMs) => setInterval(callback, intervalMs),+ clearInterval: (handle) => clearInterval(handle as ReturnType<typeof setInterval>),+ },+ pageVisibility,+ },+ onLiveChange,+ );++ return { controller, fetchLive: fetchLiveMock, onLiveChange, pageVisibility };+};++describe('WalStreamLiveController', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('reads at once and then every second', async () => {+ let localQueueBytes = 0;+ const harness = createHarness(async () => runningResponse(localQueueBytes++));++ harness.controller.start();+ await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(3 * WAL_STREAM_LIVE_INTERVAL_MS);++ expect(harness.fetchLive).toHaveBeenCalledTimes(4);+ expect(harness.onLiveChange).toHaveBeenLastCalledWith(buildLive(3));++ harness.controller.stop();+ });++ it('reports no values while no streamer runs', async () => {+ const harness = createHarness(async () => ({ isStreamerRunning: false, current: null }));++ harness.controller.start();+ await vi.advanceTimersByTimeAsync(0);++ expect(harness.onLiveChange).toHaveBeenCalledWith(null);++ harness.controller.stop();+ });++ it('does not read while the browser tab is hidden, and reads at once when it shows again', async () => {+ const harness = createHarness(async () => runningResponse(1));++ harness.controller.start();+ await vi.advanceTimersByTimeAsync(0);+ harness.pageVisibility.setVisible(false);+ await vi.advanceTimersByTimeAsync(10 * WAL_STREAM_LIVE_INTERVAL_MS);++ expect(harness.fetchLive).toHaveBeenCalledTimes(1);++ harness.pageVisibility.setVisible(true);+ await vi.advanceTimersByTimeAsync(0);++ expect(harness.fetchLive).toHaveBeenCalledTimes(2);++ harness.controller.stop();+ });++ it('keeps the last values when a reading fails', async () => {+ let isFailing = false;+ const harness = createHarness(async () => {+ if (isFailing) {+ throw new Error('network down');+ }++ return runningResponse(5);+ });++ harness.controller.start();+ await vi.advanceTimersByTimeAsync(0);+ isFailing = true;+ await vi.advanceTimersByTimeAsync(2 * WAL_STREAM_LIVE_INTERVAL_MS);++ expect(harness.onLiveChange).toHaveBeenCalledTimes(1);+ expect(harness.onLiveChange).toHaveBeenLastCalledWith(buildLive(5));++ harness.controller.stop();+ });++ it('skips a tick while the previous reading is still on its way', async () => {+ let resolveSlowReading: (response: WalStreamLiveResponse) => void = () => {};+ const harness = createHarness(+ () =>+ new Promise((resolve) => {+ resolveSlowReading = resolve;+ }),+ );++ harness.controller.start();+ await vi.advanceTimersByTimeAsync(3 * WAL_STREAM_LIVE_INTERVAL_MS);++ expect(harness.fetchLive).toHaveBeenCalledTimes(1);++ resolveSlowReading(runningResponse(1));+ await vi.advanceTimersByTimeAsync(WAL_STREAM_LIVE_INTERVAL_MS);++ expect(harness.fetchLive).toHaveBeenCalledTimes(2);++ harness.controller.stop();+ });++ it('stops reading and ignores a reading that lands after stop', async () => {+ let resolveReading: (response: WalStreamLiveResponse) => void = () => {};+ const harness = createHarness(+ () =>+ new Promise((resolve) => {+ resolveReading = resolve;+ }),+ );++ harness.controller.start();+ harness.controller.stop();+ resolveReading(runningResponse(9));+ await vi.advanceTimersByTimeAsync(5 * WAL_STREAM_LIVE_INTERVAL_MS);++ expect(harness.fetchLive).toHaveBeenCalledTimes(1);+ expect(harness.onLiveChange).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/features/backups/physical/monitoring/lib/walStreamLiveController.ts b/frontend/src/features/backups/physical/monitoring/lib/walStreamLiveController.tsnew file mode 100644index 00000000..2a3b96cd--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/lib/walStreamLiveController.ts@@ -0,0 +1,78 @@+import type { WalStreamLive, WalStreamLiveResponse } from '../../../../../entity/backups/physical';+import type { PageVisibility, RefreshTimer } from './walStreamRefreshController';++// The running streamer answers from memory, so a reading every second is cheap and makes the+// buffer and the last save move in about real time.+export const WAL_STREAM_LIVE_INTERVAL_MS = 1_000;++export interface WalStreamLiveDependencies {+ fetchLive: () => Promise<WalStreamLiveResponse>;+ timer: RefreshTimer;+ pageVisibility: PageVisibility;+}++// Reads the current values on start, every second and at once when the browser tab becomes+// visible again, never while it is hidden, and never while the previous reading is still on its+// way, so a slow server does not pile requests up. A failed reading keeps the last values: the+// statistics, refreshed on their own schedule, stay on screen underneath and say when they fail.+export class WalStreamLiveController {+ private isReading = false;+ private isStopped = false;+ private intervalHandle: unknown = null;+ private unsubscribeFromVisibility: (() => void) | null = null;++ constructor(+ private readonly dependencies: WalStreamLiveDependencies,+ private readonly onLiveChange: (live: WalStreamLive | null) => void,+ ) {}++ start() {+ this.isStopped = false;++ this.unsubscribeFromVisibility = this.dependencies.pageVisibility.subscribe(() => {+ if (this.dependencies.pageVisibility.isVisible()) {+ void this.read();+ }+ });++ this.intervalHandle = this.dependencies.timer.setInterval(() => {+ if (this.dependencies.pageVisibility.isVisible()) {+ void this.read();+ }+ }, WAL_STREAM_LIVE_INTERVAL_MS);++ void this.read();+ }++ stop() {+ this.isStopped = true;++ if (this.intervalHandle !== null) {+ this.dependencies.timer.clearInterval(this.intervalHandle);+ this.intervalHandle = null;+ }++ this.unsubscribeFromVisibility?.();+ this.unsubscribeFromVisibility = null;+ }++ private async read() {+ if (this.isReading) {+ return;+ }++ this.isReading = true;++ try {+ const response = await this.dependencies.fetchLive();++ if (!this.isStopped) {+ this.onLiveChange(response.isStreamerRunning ? response.current : null);+ }+ } catch {+ // The last values stay; the next tick tries again.+ } finally {+ this.isReading = false;+ }+ }+}diff --git a/frontend/src/features/backups/physical/monitoring/lib/walStreamRefreshController.test.ts b/frontend/src/features/backups/physical/monitoring/lib/walStreamRefreshController.test.tsindex dc464ba1..59b84f2a 100644--- a/frontend/src/features/backups/physical/monitoring/lib/walStreamRefreshController.test.ts+++ b/frontend/src/features/backups/physical/monitoring/lib/walStreamRefreshController.test.ts@@ -5,8 +5,8 @@ import {WalStreamStatisticsPeriod,} from '../../../../../entity/backups/physical';import type { WalStreamRefreshState } from '../model/WalStreamRefreshState';+import { FakePageVisibility } from './testPageVisibility';import {- type PageVisibility,WAL_STREAM_REFRESH_INTERVAL_MS,WalStreamRefreshController,} from './walStreamRefreshController';@@ -17,26 +17,6 @@ vi.hoisted(() => {vi.stubGlobal('window', {});});-class FakePageVisibility implements PageVisibility {- private isPageVisible = true;- private listeners: (() => void)[] = [];-- isVisible = () => this.isPageVisible;-- subscribe = (onVisibilityChange: () => void) => {- this.listeners.push(onVisibilityChange);-- return () => {- this.listeners = this.listeners.filter((listener) => listener !== onVisibilityChange);- };- };-- setVisible(isPageVisible: boolean) {- this.isPageVisible = isPageVisible;- this.listeners.forEach((listener) => listener());- }-}-const buildStatistics = (marker: string): WalStreamStatistics =>({ series: { from: marker } }) as unknown as WalStreamStatistics;diff --git a/frontend/src/features/backups/physical/monitoring/model/FullBackupAction.ts b/frontend/src/features/backups/physical/monitoring/model/FullBackupAction.tsnew file mode 100644index 00000000..1e2e190e--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/model/FullBackupAction.ts@@ -0,0 +1,5 @@+export enum FullBackupAction {+ HIDDEN = 'HIDDEN',+ AVAILABLE = 'AVAILABLE',+ REQUESTING = 'REQUESTING',+}diff --git a/frontend/src/features/backups/physical/monitoring/model/MissingDataRange.ts b/frontend/src/features/backups/physical/monitoring/model/MissingDataRange.tsnew file mode 100644index 00000000..cd2e8ef8--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/model/MissingDataRange.ts@@ -0,0 +1,5 @@+// A stretch of the chart's period without measurements, as epoch milliseconds.+export interface MissingDataRange {+ fromMs: number;+ toMs: number;+}diff --git a/frontend/src/features/backups/physical/monitoring/model/MonitoringFigures.ts b/frontend/src/features/backups/physical/monitoring/model/MonitoringFigures.tsnew file mode 100644index 00000000..94a1af05--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/model/MonitoringFigures.ts@@ -0,0 +1,7 @@+// The flow right now. A null value is unknown and reads as "not measured", never as zero.+export interface MonitoringFigures {+ lastSavedAt: string | null;+ waitingToBeSavedBytes: number | null;+ writeBytesPerSecond: number | null;+ saveBytesPerSecond: number | null;+}diff --git a/frontend/src/features/backups/physical/monitoring/model/MonitoringTextParam.ts b/frontend/src/features/backups/physical/monitoring/model/MonitoringTextParam.tsindex 324e22e3..14ed0ee2 100644--- a/frontend/src/features/backups/physical/monitoring/model/MonitoringTextParam.ts+++ b/frontend/src/features/backups/physical/monitoring/model/MonitoringTextParam.ts@@ -4,4 +4,6 @@ export type MonitoringTextParam =| { kind: 'bytes'; bytes: number }| { kind: 'bytesPerSecond'; bytesPerSecond: number }| { kind: 'count'; count: number }- | { kind: 'text'; text: LocalizedText };+ | { kind: 'text'; text: LocalizedText }+ // A moment from today reads as a time of day, an older one with its date.+ | { kind: 'moment'; at: string; isToday: boolean };diff --git a/frontend/src/features/backups/physical/monitoring/model/ReasonTexts.ts b/frontend/src/features/backups/physical/monitoring/model/ReasonTexts.tsindex a6108b41..263d6a19 100644--- a/frontend/src/features/backups/physical/monitoring/model/ReasonTexts.ts+++ b/frontend/src/features/backups/physical/monitoring/model/ReasonTexts.ts@@ -1,11 +1,9 @@import type { WalStreamReasonLevel } from '../../../../../entity/backups/physical';import type { TranslationKey } from '../../../../../shared/i18n';import type { MonitoringText } from './MonitoringText';-import type { PathStage } from './PathStage';export interface ReasonTexts {level: WalStreamReasonLevel;- stage: PathStage;titleKey: TranslationKey;whatHappened: MonitoringText;whatToDo: MonitoringText;diff --git a/frontend/src/features/backups/physical/monitoring/model/RestoreTimelineSegment.ts b/frontend/src/features/backups/physical/monitoring/model/RestoreTimelineSegment.tsnew file mode 100644index 00000000..fedd327a--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/model/RestoreTimelineSegment.ts@@ -0,0 +1,10 @@+import type { RestoreTimelineSegmentKind } from './RestoreTimelineSegmentKind';++// One stretch of the restore timeline, with its place on the bar in percent of the bar's width.+export interface RestoreTimelineSegment {+ kind: RestoreTimelineSegmentKind;+ fromMs: number;+ toMs: number;+ startPercent: number;+ widthPercent: number;+}diff --git a/frontend/src/features/backups/physical/monitoring/model/RestoreTimelineSegmentKind.ts b/frontend/src/features/backups/physical/monitoring/model/RestoreTimelineSegmentKind.tsnew file mode 100644index 00000000..06059064--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/model/RestoreTimelineSegmentKind.ts@@ -0,0 +1,5 @@+export enum RestoreTimelineSegmentKind {+ RESTORABLE = 'RESTORABLE',+ LOST = 'LOST',+ NOT_SAVED_YET = 'NOT_SAVED_YET',+}diff --git a/frontend/src/features/backups/physical/monitoring/model/VerdictBanner.ts b/frontend/src/features/backups/physical/monitoring/model/VerdictBanner.tsindex 098d57b3..1f6c543d 100644--- a/frontend/src/features/backups/physical/monitoring/model/VerdictBanner.ts+++ b/frontend/src/features/backups/physical/monitoring/model/VerdictBanner.ts@@ -1,6 +1,7 @@import type { TranslationKey } from '../../../../../shared/i18n';import type { MonitoringText } from './MonitoringText';import type { MonitoringTone } from './MonitoringTone';+import type { ReasonTexts } from './ReasonTexts';import type { VerdictIcon } from './VerdictIcon';export interface VerdictBanner {@@ -8,6 +9,13 @@ export interface VerdictBanner {icon: VerdictIcon;headlineKey: TranslationKey;description?: MonitoringText;++ // The most severe reason names the headline; its sentences sit right under it, and the other+ // reasons follow as compact lines.+ headlineReason?: ReasonTexts;+ otherReasons: ReasonTexts[];++ restoreSentence: MonitoringText;isConfigLinkShown: boolean;// False once refreshes have failed for too long to vouch for the verdict on screen.diff --git a/frontend/src/features/backups/physical/monitoring/ui/ChangesPathComponent.tsx b/frontend/src/features/backups/physical/monitoring/ui/ChangesPathComponent.tsxindex 81cae23f..e89d9c33 100644--- a/frontend/src/features/backups/physical/monitoring/ui/ChangesPathComponent.tsx+++ b/frontend/src/features/backups/physical/monitoring/ui/ChangesPathComponent.tsx@@ -1,21 +1,33 @@-import { ArrowDownOutlined, ArrowRightOutlined } from '@ant-design/icons';-import { Progress, Tooltip, theme } from 'antd';+import {+ ArrowDownOutlined,+ ArrowRightOutlined,+ CloseCircleFilled,+ CloudOutlined,+ CloudServerOutlined,+ DatabaseOutlined,+ ExclamationCircleFilled,+ InfoCircleOutlined,+ PauseCircleOutlined,+} from '@ant-design/icons';+import { Tooltip, theme } from 'antd';import type { ReactNode } from 'react';import { useTranslation } from 'react-i18next';import {+ WAL_STREAM_REASON_LEVEL_LABEL_KEYS,+ WalStreamReasonLevel,type WalStreamStatistics,WalStreamSourceState,} from '../../../../../entity/backups/physical';import { type TranslationKey, useLocale } from '../../../../../shared/i18n';import { formatBytes } from '../../../../../shared/lib';-import { interpolateNumber } from '../lib/easedTexts';+import { useTheme } from '../../../../../shared/theme';+import { WAL_STREAM_CHART_COLORS } from '../lib/chartColors';import { formatBytesPerSecond } from '../lib/monitoringTextValues';-import { getAmountProgress } from '../lib/pathStages';import { getToneColors } from '../lib/toneColors';-import type { MonitoringTone } from '../model/MonitoringTone';+import { MonitoringTone } from '../model/MonitoringTone';import { PathStage } from '../model/PathStage';-import { useEasedTransition } from './useEasedTransition';+import { PathAmountComponent } from './PathAmountComponent';interface Props {statistics: WalStreamStatistics;@@ -23,112 +35,180 @@ interface Props {isReducedMotion: boolean;}-interface StageCardProps {+interface StageHeaderProps {+ icon: ReactNode;titleKey: TranslationKey;tone: MonitoringTone;- children: ReactNode;+ // The line to the next stage starts right after the title, so the strip reads as one pipe.+ hasOutgoingLine?: boolean;}-interface AmountProps {+interface StageDetailsProps {labelKey: TranslationKey;tooltipKey: TranslationKey;- valueBytes: number | null;- limitBytes?: number;- isReducedMotion: boolean;+ children: ReactNode;}-interface ArrowProps {- labelKey: TranslationKey;+interface NoteProps {+ tooltipKey?: TranslationKey;+ children: ReactNode;+}++interface LinkHeaderProps {tooltipKey: TranslationKey;bytesPerSecond: number | null;}-const StageCardComponent = ({ titleKey, tone, children }: StageCardProps) => {+interface LinkLabelProps {+ labelKey: TranslationKey;+ lineColor: string;+}++// A stage without a problem stays neutral: a healthy color on every stage would read as a selection+// or an alarm. A problem adds its icon and its word, so color is never the only signal.+const PROBLEM_TONE_LEVELS: Partial<Record<MonitoringTone, WalStreamReasonLevel>> = {+ [MonitoringTone.WARNING]: WalStreamReasonLevel.NEEDS_ATTENTION,+ [MonitoringTone.ERROR]: WalStreamReasonLevel.BROKEN,+};++// On a wide section every stage and link spans the strip's two rows through a subgrid, so the+// icons and the lines share the first row and the details share the second; on a narrow one they+// stack in reading order.+// eslint-disable-next-line i18next/no-literal-string -- Tailwind classes, not copy+const STRIP_CELL_CLASS = '@2xl:row-span-2 @2xl:grid @2xl:grid-rows-subgrid';++const StageHeaderComponent = ({ icon, titleKey, tone, hasOutgoingLine }: StageHeaderProps) => {const { t } = useTranslation();const { token } = theme.useToken();+ const problemLevel = PROBLEM_TONE_LEVELS[tone];+ const toneColors = getToneColors(token, tone);+return (- <div- className="flex-1 rounded-lg border-2 bg-white p-3 dark:bg-gray-800"- style={{ borderColor: getToneColors(token, tone).border }}- >- <div className="mb-2 font-semibold">{t(titleKey)}</div>- <div className="space-y-2 text-sm">{children}</div>+ <div className="flex items-center gap-x-2 @2xl:h-9">+ <span+ aria-hidden+ className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full border text-base"+ style={+ problemLevel+ ? {+ borderColor: toneColors.border,+ backgroundColor: toneColors.background,+ color: toneColors.icon,+ }+ : { borderColor: token.colorBorderSecondary, color: token.colorTextSecondary }+ }+ >+ {icon}+ </span>++ <span className="font-semibold">{t(titleKey)}</span>++ {problemLevel && (+ <span+ className="flex items-center gap-1 text-xs font-medium"+ style={{ color: toneColors.icon }}+ >+ {problemLevel === WalStreamReasonLevel.BROKEN ? (+ <CloseCircleFilled aria-hidden />+ ) : (+ <ExclamationCircleFilled aria-hidden />+ )}+ {t(WAL_STREAM_REASON_LEVEL_LABEL_KEYS[problemLevel])}+ </span>+ )}++ {hasOutgoingLine && (+ <span+ className="ml-1 hidden h-px min-w-3 flex-1 bg-gray-300 @2xl:block dark:bg-gray-600"+ aria-hidden+ />+ )}</div>);};-const easeAmount = (fromBytes: number, toBytes: number, progress: number) =>- interpolateNumber(fromBytes, toBytes, progress);--const AmountComponent = ({- labelKey,- tooltipKey,- valueBytes,- limitBytes,- isReducedMotion,-}: AmountProps) => {+const InfoTooltipComponent = ({ tooltipKey }: { tooltipKey: TranslationKey }) => {const { t } = useTranslation();- const { formatNumber } = useLocale();- const easedBytes = useEasedTransition(valueBytes ?? 0, easeAmount, isReducedMotion);+ return (+ <Tooltip title={t(tooltipKey)}>+ <InfoCircleOutlined+ tabIndex={0}+ aria-label={t(tooltipKey)}+ className="cursor-help text-gray-400 dark:text-gray-500"+ />+ </Tooltip>+ );+};- const progress =- valueBytes !== null && limitBytes !== undefined- ? getAmountProgress(valueBytes, limitBytes)- : null;+const StageDetailsComponent = ({ labelKey, tooltipKey, children }: StageDetailsProps) => {+ const { t } = useTranslation();return (- <div>- <Tooltip title={t(tooltipKey)}>- <span tabIndex={0} className="cursor-help border-b border-dotted border-gray-400">- {t(labelKey)}- </span>- </Tooltip>-- <div className="font-semibold">- {valueBytes === null- ? t('backups.physical.monitoring.path.unknownAmount')- : formatBytes(easedBytes, formatNumber)}+ <div className="mt-2 space-y-1.5 pr-3 pl-11">+ {/* Inline, so the info icon follows the last word when the label wraps. */}+ <div className="text-xs text-gray-600 dark:text-gray-400">+ {t(labelKey)} <InfoTooltipComponent tooltipKey={tooltipKey} /></div>-- {progress && (- <>- <Progress- percent={progress.percent}- showInfo={false}- size="small"- status={progress.isOverLimit ? 'exception' : 'normal'}- />- {progress.isOverLimit && (- <div className="text-xs font-semibold text-red-600 dark:text-red-400">- {t('backups.physical.monitoring.path.overLimit')}- </div>- )}- </>- )}+ {children}</div>);};-const ArrowComponent = ({ labelKey, tooltipKey, bytesPerSecond }: ArrowProps) => {+const NoteComponent = ({ tooltipKey, children }: NoteProps) => (+ <div className="flex items-start gap-1.5 text-xs text-gray-600 dark:text-gray-400">+ <span>{children}</span>+ {tooltipKey && <InfoTooltipComponent tooltipKey={tooltipKey} />}+ </div>+);++// The rate sits on the line between two stages, like the throughput of a pipe.+const LinkHeaderComponent = ({ tooltipKey, bytesPerSecond }: LinkHeaderProps) => {const { t } = useTranslation();const { formatNumber } = useLocale();- const rate =- bytesPerSecond === null- ? t('backups.physical.monitoring.path.unknownAmount')- : formatBytesPerSecond(bytesPerSecond, t, formatNumber);-return (- <div className="flex flex-col items-center justify-center px-2 text-xs text-gray-600 dark:text-gray-400">+ <div className="flex items-center justify-center pt-2 text-gray-400 @2xl:h-9 @2xl:pt-0 @2xl:pr-2">+ {/* The container breakpoint classes sit on wrappers: AntD's own icon display rule would+ override them on the icon element and show both arrows. */}+ <span className="hidden h-px flex-1 bg-gray-300 @2xl:block dark:bg-gray-600" aria-hidden />+<Tooltip title={t(tooltipKey)}>- <span tabIndex={0} className="cursor-help text-center">- {t(labelKey, { rate })}+ <span+ tabIndex={0}+ className="mx-1 cursor-help rounded-full border border-gray-200 px-2 py-0.5 text-sm font-semibold whitespace-nowrap text-gray-900 tabular-nums dark:border-gray-600 dark:text-gray-100"+ >+ {bytesPerSecond === null+ ? t('backups.physical.monitoring.path.unknownAmount')+ : formatBytesPerSecond(bytesPerSecond, t, formatNumber)}</span></Tooltip>- <ArrowRightOutlined className="hidden text-lg md:block" aria-hidden />- <ArrowDownOutlined className="text-lg md:hidden" aria-hidden />++ <span className="hidden h-px flex-1 bg-gray-300 @2xl:block dark:bg-gray-600" aria-hidden />+ <span className="hidden @2xl:block" aria-hidden>+ <ArrowRightOutlined />+ </span>+ </div>+ );+};++const LinkLabelComponent = ({ labelKey, lineColor }: LinkLabelProps) => {+ const { t } = useTranslation();++ return (+ <div className="flex flex-col items-center gap-1 pb-2 @2xl:pb-0">+ <span className="flex items-center gap-1.5 text-xs text-gray-600 dark:text-gray-400">+ <span+ aria-hidden+ className="inline-block h-2 w-2 shrink-0 rounded-full"+ style={{ backgroundColor: lineColor }}+ />+ {t(labelKey)}+ </span>+ <span className="block text-gray-400 @2xl:hidden" aria-hidden>+ <ArrowDownOutlined />+ </span></div>);};@@ -136,103 +216,142 @@ const ArrowComponent = ({ labelKey, tooltipKey, bytesPerSecond }: ArrowProps) =>export const ChangesPathComponent = ({ statistics, stageTones, isReducedMotion }: Props) => {const { t } = useTranslation();const { formatNumber, formatRelativeTime } = useLocale();+ const { resolvedTheme } = useTheme();+ const chartColors = WAL_STREAM_CHART_COLORS[resolvedTheme];const { current, keepingUp } = statistics;- const isSourceReachable = current?.sourceState === WalStreamSourceState.REACHABLE;const slotRebuildLagBytes = keepingUp.slotRebuildLagBytes;+ const slotLagBytes = current?.slotLagBytes ?? null;+ const localQueueBytes = current?.localQueueBytes ?? null;return (- <div className="mt-4 flex flex-col items-stretch md:flex-row">- <StageCardComponent- titleKey="backups.physical.monitoring.path.database"- tone={stageTones[PathStage.SOURCE]}- >- <AmountComponent- labelKey="backups.physical.monitoring.path.notReceivedYet"- tooltipKey="backups.physical.monitoring.tooltips.notReceivedYet"- valueBytes={current?.slotLagBytes ?? null}- limitBytes={slotRebuildLagBytes > 0 ? slotRebuildLagBytes : undefined}- isReducedMotion={isReducedMotion}- />+ <div className="rounded-lg border border-gray-200 p-4 dark:border-gray-700">+ <div className="@container">+ <ol className="grid grid-cols-1 @2xl:grid-cols-[minmax(0,1fr)_minmax(104px,140px)_minmax(0,1fr)_minmax(104px,140px)_minmax(0,1fr)] @2xl:grid-rows-[auto_auto]">+ <li className={STRIP_CELL_CLASS}>+ <StageHeaderComponent+ icon={<DatabaseOutlined />}+ titleKey="backups.physical.monitoring.path.database"+ hasOutgoingLine+ tone={stageTones[PathStage.SOURCE]}+ />+ <StageDetailsComponent+ labelKey="backups.physical.monitoring.path.notReceivedYet"+ tooltipKey="backups.physical.monitoring.tooltips.notReceivedYet"+ >+ <PathAmountComponent+ valueBytes={slotLagBytes}+ limitBytes={slotRebuildLagBytes > 0 ? slotRebuildLagBytes : undefined}+ isReducedMotion={isReducedMotion}+ />- {slotRebuildLagBytes > 0 && (- <Tooltip title={t('backups.physical.monitoring.tooltips.rebuildLimit')}>- <div tabIndex={0} className="cursor-help text-xs text-gray-600 dark:text-gray-400">- {t('backups.physical.monitoring.path.rebuildLimit', {- amount: formatBytes(slotRebuildLagBytes, formatNumber),- })}- </div>- </Tooltip>- )}-- {isSourceReachable && (- <Tooltip title={t('backups.physical.monitoring.tooltips.allowanceLeft')}>- <div tabIndex={0} className="cursor-help text-xs text-gray-600 dark:text-gray-400">- {current?.slotSafeWalSizeBytes != null- ? t('backups.physical.monitoring.path.allowanceLeft', {- amount: formatBytes(current.slotSafeWalSizeBytes, formatNumber),- })- : t('backups.physical.monitoring.path.noAllowanceLimit')}- </div>- </Tooltip>- )}- </StageCardComponent>-- <ArrowComponent- labelKey="backups.physical.monitoring.path.writeRate"- tooltipKey="backups.physical.monitoring.tooltips.writeRate"- bytesPerSecond={keepingUp.sourceWriteBytesPerSecond}- />+ {/* A limit matters once something waits; until then it stays in the tooltip. */}+ {slotRebuildLagBytes > 0 && slotLagBytes !== null && slotLagBytes > 0 && (+ <NoteComponent tooltipKey="backups.physical.monitoring.tooltips.rebuildLimit">+ {t('backups.physical.monitoring.path.rebuildLimit', {+ amount: formatBytes(slotRebuildLagBytes, formatNumber),+ })}+ </NoteComponent>+ )}- <StageCardComponent- titleKey="backups.physical.monitoring.path.databasus"- tone={stageTones[PathStage.DATABASUS]}- >- <AmountComponent- labelKey="backups.physical.monitoring.path.waitingInBuffer"- tooltipKey="backups.physical.monitoring.tooltips.waitingInBuffer"- valueBytes={current?.localQueueBytes ?? null}- limitBytes={current?.localQueuePauseBytes}- isReducedMotion={isReducedMotion}- />+ {current?.sourceState === WalStreamSourceState.REACHABLE &&+ current.slotSafeWalSizeBytes != null && (+ <NoteComponent tooltipKey="backups.physical.monitoring.tooltips.allowanceLeft">+ {t('backups.physical.monitoring.path.allowanceLeft', {+ amount: formatBytes(current.slotSafeWalSizeBytes, formatNumber),+ })}+ </NoteComponent>+ )}+ </StageDetailsComponent>+ </li>- {current && (- <Tooltip title={t('backups.physical.monitoring.tooltips.pauseLimit')}>- <div tabIndex={0} className="cursor-help text-xs text-gray-600 dark:text-gray-400">- {t('backups.physical.monitoring.path.pauseLimit', {- amount: formatBytes(current.localQueuePauseBytes, formatNumber),- })}- </div>- </Tooltip>- )}-- {current && !current.isReceiverRunning && (- <div className="text-xs font-semibold">- {t('backups.physical.monitoring.path.receivingPaused')}- </div>- )}- </StageCardComponent>-- <ArrowComponent- labelKey="backups.physical.monitoring.path.saveRate"- tooltipKey="backups.physical.monitoring.tooltips.saveRate"- bytesPerSecond={keepingUp.archiveBytesPerSecond}- />+ <li className={STRIP_CELL_CLASS}>+ <LinkHeaderComponent+ tooltipKey="backups.physical.monitoring.tooltips.writeRate"+ bytesPerSecond={keepingUp.sourceWriteBytesPerSecond}+ />+ <LinkLabelComponent+ labelKey="backups.physical.monitoring.charts.databaseWrites"+ lineColor={chartColors.sourceWrites}+ />+ </li>- <StageCardComponent- titleKey="backups.physical.monitoring.path.storage"- tone={stageTones[PathStage.STORAGE]}- >- <Tooltip title={t('backups.physical.monitoring.tooltips.lastSaved')}>- <div tabIndex={0} className="cursor-help">- {current?.lastArchivedWalAt- ? t('backups.physical.monitoring.path.lastSaved', {- relativeTime: formatRelativeTime(current.lastArchivedWalAt),- })- : t('backups.physical.monitoring.path.nothingSavedYet')}- </div>- </Tooltip>- </StageCardComponent>+ <li className={STRIP_CELL_CLASS}>+ <StageHeaderComponent+ icon={<CloudServerOutlined />}+ titleKey="backups.physical.monitoring.path.databasus"+ hasOutgoingLine+ tone={stageTones[PathStage.DATABASUS]}+ />+ <StageDetailsComponent+ labelKey="backups.physical.monitoring.path.waitingInBuffer"+ tooltipKey="backups.physical.monitoring.tooltips.waitingInBuffer"+ >+ <PathAmountComponent+ valueBytes={localQueueBytes}+ limitBytes={current?.localQueuePauseBytes}+ isReducedMotion={isReducedMotion}+ />++ {current && localQueueBytes !== null && localQueueBytes > 0 && (+ <NoteComponent tooltipKey="backups.physical.monitoring.tooltips.pauseLimit">+ {t('backups.physical.monitoring.path.pauseLimit', {+ amount: formatBytes(current.localQueuePauseBytes, formatNumber),+ })}+ </NoteComponent>+ )}++ {current && !current.isReceiverRunning && (+ <div className="flex items-center gap-1.5 text-xs font-semibold text-orange-600 dark:text-orange-400">+ <PauseCircleOutlined aria-hidden />+ {t('backups.physical.monitoring.path.receivingPaused')}+ </div>+ )}+ </StageDetailsComponent>+ </li>++ <li className={STRIP_CELL_CLASS}>+ <LinkHeaderComponent+ tooltipKey="backups.physical.monitoring.tooltips.saveRate"+ bytesPerSecond={keepingUp.archiveBytesPerSecond}+ />+ <LinkLabelComponent+ labelKey="backups.physical.monitoring.charts.savedToStorage"+ lineColor={chartColors.archive}+ />+ </li>++ <li className={STRIP_CELL_CLASS}>+ <StageHeaderComponent+ icon={<CloudOutlined />}+ titleKey="backups.physical.monitoring.path.storage"+ tone={stageTones[PathStage.STORAGE]}+ />+ <StageDetailsComponent+ labelKey="backups.physical.monitoring.figures.lastSaved"+ tooltipKey="backups.physical.monitoring.tooltips.lastSaved"+ >+ <div className="text-base font-semibold">+ {current?.lastArchivedWalAt+ ? formatRelativeTime(current.lastArchivedWalAt)+ : t('backups.physical.monitoring.path.nothingSavedYet')}+ </div>++ {current?.unarchivedWalBytes != null && (+ <NoteComponent tooltipKey="backups.physical.monitoring.tooltips.notSavedYet">+ {t('backups.physical.monitoring.path.notSavedYetAmount', {+ amount: formatBytes(current.unarchivedWalBytes, formatNumber),+ })}+ </NoteComponent>+ )}+ </StageDetailsComponent>+ </li>+ </ol>+ </div>++ <p className="mt-4 mb-0 text-xs text-gray-600 dark:text-gray-400">+ {t('backups.physical.monitoring.path.ratesCaption')}+ </p></div>);};diff --git a/frontend/src/features/backups/physical/monitoring/ui/MonitoringFiguresComponent.tsx b/frontend/src/features/backups/physical/monitoring/ui/MonitoringFiguresComponent.tsxnew file mode 100644index 00000000..baf81829--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/ui/MonitoringFiguresComponent.tsx@@ -0,0 +1,137 @@+import type { ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import { type TranslationKey, useLocale } from '../../../../../shared/i18n';+import { formatBytes } from '../../../../../shared/lib';+import { useTheme } from '../../../../../shared/theme';+import { WAL_STREAM_CHART_COLORS } from '../lib/chartColors';+import { interpolateMonitoringTexts, interpolateNumber } from '../lib/easedTexts';+import { formatBytesPerSecond } from '../lib/monitoringTextValues';+import type { MonitoringFigures } from '../model/MonitoringFigures';+import type { MonitoringText } from '../model/MonitoringText';+import { MonitoringTextComponent } from './MonitoringTextComponent';+import { useEasedTransition } from './useEasedTransition';++interface Props {+ figures: MonitoringFigures;+ keepingUpSentences: MonitoringText[];+ isReducedMotion: boolean;+}++interface FigureProps {+ labelKey: TranslationKey;+ // The color of the chart line this figure belongs to.+ lineColor?: string;+ // Rates are averages over a window while amounts are current, which the card has to say, or a+ // rate next to an empty queue reads as a contradiction.+ isAverage?: boolean;+ children: ReactNode;+}++const FigureComponent = ({ labelKey, lineColor, isAverage, children }: FigureProps) => {+ const { t } = useTranslation();++ return (+ <div className="rounded-lg border border-gray-200 px-4 py-3 dark:border-gray-700">+ <div className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400">+ {lineColor && (+ <span+ aria-hidden+ className="inline-block h-2.5 w-2.5 shrink-0 rounded-full"+ style={{ backgroundColor: lineColor }}+ />+ )}+ {t(labelKey)}+ {isAverage && (+ <span className="text-xs text-gray-400 dark:text-gray-500">+ {t('backups.physical.monitoring.figures.averageHint')}+ </span>+ )}+ </div>+ <div className="mt-1 text-xl font-semibold tabular-nums">{children}</div>+ </div>+ );+};++export const MonitoringFiguresComponent = ({+ figures,+ keepingUpSentences,+ isReducedMotion,+}: Props) => {+ const { t } = useTranslation();+ const { formatNumber, formatRelativeTime } = useLocale();+ const { resolvedTheme } = useTheme();++ const chartColors = WAL_STREAM_CHART_COLORS[resolvedTheme];++ const easedWaitingBytes = useEasedTransition(+ figures.waitingToBeSavedBytes ?? 0,+ interpolateNumber,+ isReducedMotion,+ );+ const easedWriteRate = useEasedTransition(+ figures.writeBytesPerSecond ?? 0,+ interpolateNumber,+ isReducedMotion,+ );+ const easedSaveRate = useEasedTransition(+ figures.saveBytesPerSecond ?? 0,+ interpolateNumber,+ isReducedMotion,+ );+ const easedSentences = useEasedTransition(+ keepingUpSentences,+ interpolateMonitoringTexts,+ isReducedMotion,+ );++ const notMeasured = t('backups.physical.monitoring.figures.notMeasured');++ return (+ <div className="mt-4">+ <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">+ <FigureComponent labelKey="backups.physical.monitoring.figures.lastSaved">+ {figures.lastSavedAt+ ? formatRelativeTime(figures.lastSavedAt)+ : t('backups.physical.monitoring.path.nothingSavedYet')}+ </FigureComponent>++ <FigureComponent labelKey="backups.physical.monitoring.figures.waitingToBeSaved">+ {figures.waitingToBeSavedBytes === null+ ? notMeasured+ : formatBytes(easedWaitingBytes, formatNumber)}+ </FigureComponent>++ <FigureComponent+ labelKey="backups.physical.monitoring.charts.databaseWrites"+ lineColor={chartColors.sourceWrites}+ isAverage+ >+ {figures.writeBytesPerSecond === null+ ? notMeasured+ : formatBytesPerSecond(easedWriteRate, t, formatNumber)}+ </FigureComponent>++ <FigureComponent+ labelKey="backups.physical.monitoring.charts.savedToStorage"+ lineColor={chartColors.archive}+ isAverage+ >+ {figures.saveBytesPerSecond === null+ ? notMeasured+ : formatBytesPerSecond(easedSaveRate, t, formatNumber)}+ </FigureComponent>+ </div>++ {easedSentences.length > 0 && (+ <div className="mt-2 text-sm text-gray-600 dark:text-gray-400">+ {easedSentences.map((sentence) => (+ <span key={sentence.key} className="mr-1">+ <MonitoringTextComponent text={sentence} />+ </span>+ ))}+ </div>+ )}+ </div>+ );+};diff --git a/frontend/src/features/backups/physical/monitoring/ui/MonitoringReasonsComponent.tsx b/frontend/src/features/backups/physical/monitoring/ui/MonitoringReasonsComponent.tsxdeleted file mode 100644index ed747b42..00000000--- a/frontend/src/features/backups/physical/monitoring/ui/MonitoringReasonsComponent.tsx+++ /dev/null@@ -1,97 +0,0 @@-import { CloseCircleFilled, ExclamationCircleFilled } from '@ant-design/icons';-import { Alert, Collapse, theme } from 'antd';-import { useTranslation } from 'react-i18next';--import { WalStreamNoticeCode, WalStreamReasonLevel } from '../../../../../entity/backups/physical';-import type { ReasonTexts } from '../model/ReasonTexts';-import { MonitoringTextComponent } from './MonitoringTextComponent';--interface Props {- reasons: ReasonTexts[];- notices: { code: WalStreamNoticeCode; texts: ReasonTexts }[];-}--export const MonitoringReasonsComponent = ({ reasons, notices }: Props) => {- const { t } = useTranslation();- const { token } = theme.useToken();-- if (reasons.length === 0 && notices.length === 0) {- return null;- }-- return (- <div className="mt-4 space-y-3">- {reasons.length > 0 && (- <ul className="space-y-3">- {reasons.map((reason) => {- const isBroken = reason.level === WalStreamReasonLevel.BROKEN;-- return (- <li key={reason.titleKey} className="flex items-start gap-3">- <span- className="mt-0.5 text-lg leading-none"- style={{ color: isBroken ? token.colorError : token.colorWarning }}- aria-hidden- >- {isBroken ? <CloseCircleFilled /> : <ExclamationCircleFilled />}- </span>-- <div>- <div className="font-semibold">{t(reason.titleKey)}</div>- <div>- <MonitoringTextComponent text={reason.whatHappened} />- </div>- <div className="text-gray-600 dark:text-gray-400">- <MonitoringTextComponent text={reason.whatToDo} />- </div>- </div>- </li>- );- })}- </ul>- )}-- {notices.length > 0 && (- <Alert- type="info"- showIcon- message={- <div className="space-y-2">- {notices.map(({ code, texts }) =>- code === WalStreamNoticeCode.NO_SLOT_WAL_LIMIT ? (- <Collapse- key={code}- ghost- size="small"- items={[- {- key: code,- label: (- <div>- <div className="font-semibold">{t(texts.titleKey)}</div>- <MonitoringTextComponent text={texts.whatHappened} />- </div>- ),- children: <MonitoringTextComponent text={texts.whatToDo} />,- },- ]}- />- ) : (- <div key={code}>- <div className="font-semibold">{t(texts.titleKey)}</div>- <div>- <MonitoringTextComponent text={texts.whatHappened} />- </div>- <div className="text-gray-600 dark:text-gray-400">- <MonitoringTextComponent text={texts.whatToDo} />- </div>- </div>- ),- )}- </div>- }- />- )}- </div>- );-};diff --git a/frontend/src/features/backups/physical/monitoring/ui/MonitoringTipsComponent.tsx b/frontend/src/features/backups/physical/monitoring/ui/MonitoringTipsComponent.tsxnew file mode 100644index 00000000..c2848cd8--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/ui/MonitoringTipsComponent.tsx@@ -0,0 +1,40 @@+import { InfoCircleOutlined } from '@ant-design/icons';+import { useTranslation } from 'react-i18next';++import type { ReasonTexts } from '../model/ReasonTexts';+import { MonitoringTextComponent } from './MonitoringTextComponent';++interface Props {+ tips: ReasonTexts[];+}++// Tips never change the verdict, so they sit among the technical details as quiet notes instead of+// competing with it.+export const MonitoringTipsComponent = ({ tips }: Props) => {+ const { t } = useTranslation();++ if (tips.length === 0) {+ return null;+ }++ return (+ <ul className="space-y-3 text-sm">+ {tips.map((tip) => (+ <li key={tip.titleKey} className="flex gap-2">+ <span className="shrink-0 pt-0.5 text-gray-400 dark:text-gray-500" aria-hidden>+ <InfoCircleOutlined />+ </span>+ <div>+ <div className="font-semibold">{t(tip.titleKey)}</div>+ <div>+ <MonitoringTextComponent text={tip.whatHappened} />+ </div>+ <div className="text-gray-600 dark:text-gray-400">+ <MonitoringTextComponent text={tip.whatToDo} />+ </div>+ </div>+ </li>+ ))}+ </ul>+ );+};diff --git a/frontend/src/features/backups/physical/monitoring/ui/PathAmountComponent.tsx b/frontend/src/features/backups/physical/monitoring/ui/PathAmountComponent.tsxnew file mode 100644index 00000000..771ce051--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/ui/PathAmountComponent.tsx@@ -0,0 +1,83 @@+import { CheckCircleOutlined } from '@ant-design/icons';+import { theme } from 'antd';+import { useTranslation } from 'react-i18next';++import { useLocale } from '../../../../../shared/i18n';+import { formatBytes } from '../../../../../shared/lib';+import { interpolateNumber } from '../lib/easedTexts';+import { getAmountProgress } from '../lib/pathStages';+import { useEasedTransition } from './useEasedTransition';++interface Props {+ valueBytes: number | null;+ limitBytes?: number;+ isReducedMotion: boolean;+}++const easeAmount = (fromBytes: number, toBytes: number, progress: number) =>+ interpolateNumber(fromBytes, toBytes, progress);++// An empty queue says "nothing waiting" instead of a bold 0 B over an empty meter, which read as+// broken. A filled queue shows the amount and, with a limit, "X of Y" under a thin meter.+export const PathAmountComponent = ({ valueBytes, limitBytes, isReducedMotion }: Props) => {+ const { t } = useTranslation();+ const { formatNumber } = useLocale();+ const { token } = theme.useToken();++ const easedBytes = useEasedTransition(valueBytes ?? 0, easeAmount, isReducedMotion);++ if (valueBytes === null) {+ return (+ <div className="text-sm text-gray-600 dark:text-gray-400">+ {t('backups.physical.monitoring.path.unknownAmount')}+ </div>+ );+ }++ if (valueBytes === 0) {+ return (+ <div className="flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400">+ <CheckCircleOutlined aria-hidden style={{ color: token.colorSuccess }} />+ {t('backups.physical.monitoring.path.nothingWaiting')}+ </div>+ );+ }++ const progress = limitBytes === undefined ? null : getAmountProgress(valueBytes, limitBytes);++ return (+ <div>+ <div className="text-base font-semibold tabular-nums">+ {formatBytes(easedBytes, formatNumber)}+ </div>++ {progress && limitBytes !== undefined && (+ <div className="mt-1 max-w-48">+ <div className="h-1.5 w-full overflow-hidden rounded-full bg-gray-100 dark:bg-gray-700">+ <div+ className="h-full rounded-full"+ style={{+ width: `${progress.percent}%`,+ backgroundColor: progress.isOverLimit ? token.colorError : token.colorPrimary,+ transition: isReducedMotion ? undefined : 'width 300ms',+ }}+ />+ </div>++ <div className="mt-0.5 text-xs text-gray-600 dark:text-gray-400">+ {progress.isOverLimit ? (+ <span className="font-semibold text-red-600 dark:text-red-400">+ {t('backups.physical.monitoring.path.overLimit')}+ </span>+ ) : (+ t('backups.physical.monitoring.path.ofLimit', {+ amount: formatBytes(valueBytes, formatNumber),+ limit: formatBytes(limitBytes, formatNumber),+ })+ )}+ </div>+ </div>+ )}+ </div>+ );+};diff --git a/frontend/src/features/backups/physical/monitoring/ui/RestoreTimelineComponent.tsx b/frontend/src/features/backups/physical/monitoring/ui/RestoreTimelineComponent.tsxnew file mode 100644index 00000000..e21bd463--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/ui/RestoreTimelineComponent.tsx@@ -0,0 +1,122 @@+import { Tooltip, theme } from 'antd';+import { useTranslation } from 'react-i18next';++import type { WalStreamTimeRange } from '../../../../../entity/backups/physical';+import type { TranslationKey } from '../../../../../shared/i18n';+import { formatMoment } from '../lib/monitoringTextValues';+import {+ getLostStretchTexts,+ getMomentParam,+ getRestoreTimeline,+ getSegmentRangeText,+} from '../lib/restoreTimeline';+import { RestoreTimelineSegmentKind } from '../model/RestoreTimelineSegmentKind';+import { MonitoringTextComponent } from './MonitoringTextComponent';++interface Props {+ ranges: WalStreamTimeRange[];+ now: Date;+}++const SEGMENT_LABEL_KEYS: Record<RestoreTimelineSegmentKind, TranslationKey> = {+ [RestoreTimelineSegmentKind.RESTORABLE]: 'backups.physical.monitoring.restoreTimeline.restorable',+ [RestoreTimelineSegmentKind.LOST]: 'backups.physical.monitoring.restoreTimeline.lost',+ [RestoreTimelineSegmentKind.NOT_SAVED_YET]:+ 'backups.physical.monitoring.restoreTimeline.notSavedYet',+};++const SEGMENT_KINDS = [+ RestoreTimelineSegmentKind.RESTORABLE,+ RestoreTimelineSegmentKind.LOST,+ RestoreTimelineSegmentKind.NOT_SAVED_YET,+];++const useSegmentBackgrounds = (): Record<RestoreTimelineSegmentKind, string> => {+ const { token } = theme.useToken();++ return {+ [RestoreTimelineSegmentKind.RESTORABLE]: token.colorSuccess,+ // Hatched as well as muted red, so the lost stretch stands apart without color and an old gap+ // does not shout next to a green banner.+ // eslint-disable-next-line i18next/no-literal-string -- CSS value, not copy+ [RestoreTimelineSegmentKind.LOST]: `repeating-linear-gradient(135deg, ${token.colorErrorBorder} 0 3px, ${token.colorErrorBg} 3px 6px)`,+ [RestoreTimelineSegmentKind.NOT_SAVED_YET]: token.colorTextQuaternary,+ };+};++export const RestoreTimelineComponent = ({ ranges, now }: Props) => {+ const { t } = useTranslation();+ const segmentBackgrounds = useSegmentBackgrounds();++ const segments = getRestoreTimeline(ranges, now);++ if (segments.length === 0) {+ return null;+ }++ const shownKinds = SEGMENT_KINDS.filter((kind) =>+ segments.some((segment) => segment.kind === kind),+ );+ const lostStretchTexts = getLostStretchTexts(segments, now);++ return (+ <div className="mt-6">+ <div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-1">+ <div className="font-semibold">+ {t('backups.physical.monitoring.restoreTimeline.title')}+ </div>++ <ul className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-gray-600 dark:text-gray-400">+ {shownKinds.map((kind) => (+ <li key={kind} className="flex items-center gap-1.5">+ <span+ aria-hidden+ className="inline-block h-2.5 w-4 shrink-0 rounded-sm"+ style={{ background: segmentBackgrounds[kind] }}+ />+ {t(SEGMENT_LABEL_KEYS[kind])}+ </li>+ ))}+ </ul>+ </div>++ <div className="relative mt-2 h-3 w-full overflow-hidden rounded-full bg-gray-100 dark:bg-gray-700">+ {segments.map((segment) => (+ <Tooltip+ key={`${segment.kind}-${segment.fromMs}`}+ title={+ <div>+ <div className="font-semibold">{t(SEGMENT_LABEL_KEYS[segment.kind])}</div>+ <MonitoringTextComponent text={getSegmentRangeText(segment, now)} />+ </div>+ }+ >+ <div+ className="absolute top-0 h-full"+ style={{+ left: `${segment.startPercent}%`,+ width: `${segment.widthPercent}%`,+ background: segmentBackgrounds[segment.kind],+ }}+ />+ </Tooltip>+ ))}+ </div>++ <div className="mt-1 flex justify-between text-xs text-gray-600 dark:text-gray-400">+ <span>{formatMoment(getMomentParam(segments[0].fromMs, now))}</span>+ <span>{formatMoment(getMomentParam(segments[segments.length - 1].toMs, now))}</span>+ </div>++ {lostStretchTexts.length > 0 && (+ <ul className="mt-2 space-y-1 text-sm">+ {lostStretchTexts.map((text, index) => (+ <li key={index}>+ <MonitoringTextComponent text={text} />+ </li>+ ))}+ </ul>+ )}+ </div>+ );+};diff --git a/frontend/src/features/backups/physical/monitoring/ui/TechnicalDetailsComponent.tsx b/frontend/src/features/backups/physical/monitoring/ui/TechnicalDetailsComponent.tsxnew file mode 100644index 00000000..e324a74c--- /dev/null+++ b/frontend/src/features/backups/physical/monitoring/ui/TechnicalDetailsComponent.tsx@@ -0,0 +1,59 @@+import { useTranslation } from 'react-i18next';++import type { WalStreamStatistics } from '../../../../../entity/backups/physical';+import type { MonitoringTone } from '../model/MonitoringTone';+import type { PathStage } from '../model/PathStage';+import type { ReasonTexts } from '../model/ReasonTexts';+import { ChangesPathComponent } from './ChangesPathComponent';+import { MonitoringTipsComponent } from './MonitoringTipsComponent';+import { WalStreamTechnicalChartsComponent } from './WalStreamChartsComponent';+import { WalStreamRawValuesComponent } from './WalStreamRawValuesComponent';++interface Props {+ statistics: WalStreamStatistics;+ stageTones: Record<PathStage, MonitoringTone>;+ tips: ReasonTexts[];+ isReducedMotion: boolean;+ isChartAnimationActive: boolean;+}++// Without a sample the segment size is unknown; 16 MiB is PostgreSQL's default.+const DEFAULT_WAL_SEGMENT_SIZE_BYTES = 16 * 1024 * 1024;++// The figures stay in view under the verdict instead of behind a click: a reader checking why the+// verdict says what it does should not have to look for them.+export const TechnicalDetailsComponent = ({+ statistics,+ stageTones,+ tips,+ isReducedMotion,+ isChartAnimationActive,+}: Props) => {+ const { t } = useTranslation();++ return (+ <section className="mt-8 space-y-6 border-t border-gray-200 pt-6 dark:border-gray-700">+ <h3 className="text-base font-semibold">+ {t('backups.physical.monitoring.technicalDetails.title')}+ </h3>++ <ChangesPathComponent+ statistics={statistics}+ stageTones={stageTones}+ isReducedMotion={isReducedMotion}+ />++ <MonitoringTipsComponent tips={tips} />++ <WalStreamTechnicalChartsComponent+ series={statistics.series}+ walSegmentSizeBytes={+ statistics.current?.walSegmentSizeBytes ?? DEFAULT_WAL_SEGMENT_SIZE_BYTES+ }+ isAnimationActive={isChartAnimationActive}+ />++ <WalStreamRawValuesComponent statistics={statistics} />+ </section>+ );+};diff --git a/frontend/src/features/backups/physical/monitoring/ui/VerdictBannerComponent.tsx b/frontend/src/features/backups/physical/monitoring/ui/VerdictBannerComponent.tsxindex 8c629841..2538ab17 100644--- a/frontend/src/features/backups/physical/monitoring/ui/VerdictBannerComponent.tsx+++ b/frontend/src/features/backups/physical/monitoring/ui/VerdictBannerComponent.tsx@@ -6,27 +6,28 @@ import {PauseCircleFilled,QuestionCircleFilled,} from '@ant-design/icons';-import { theme } from 'antd';+import { Button, theme } from 'antd';import type { ReactNode } from 'react';import { useTranslation } from 'react-i18next';+import { WalStreamReasonLevel } from '../../../../../entity/backups/physical';import { translateLocalizedText } from '../../../../../shared/i18n';-import { interpolateMonitoringTexts } from '../lib/easedTexts';import { getMeasurementAge, getSecondsBetween } from '../lib/roundedDuration';import { getToneColors } from '../lib/toneColors';import { UNCONFIRMED_STATE_AFTER_MS } from '../lib/verdictBanner';-import type { MonitoringText } from '../model/MonitoringText';+import { FullBackupAction } from '../model/FullBackupAction';+import type { ReasonTexts } from '../model/ReasonTexts';import type { VerdictBanner } from '../model/VerdictBanner';import { VerdictIcon } from '../model/VerdictIcon';import { MonitoringTextComponent } from './MonitoringTextComponent';-import { useEasedTransition } from './useEasedTransition';interface Props {banner: VerdictBanner;- keepingUpSentences: MonitoringText[];+ fullBackupAction: FullBackupAction;sampledAt: string | null;now: Date;isReducedMotion: boolean;+ onStartFullBackup: () => void;onOpenConfig: () => void;}@@ -39,81 +40,138 @@ const VERDICT_ICONS: Record<VerdictIcon, ReactNode> = {[VerdictIcon.QUESTION]: <QuestionCircleFilled />,};+const OtherReasonComponent = ({ reason }: { reason: ReasonTexts }) => {+ const { t } = useTranslation();+ const { token } = theme.useToken();++ const isBroken = reason.level === WalStreamReasonLevel.BROKEN;++ return (+ <li className="flex items-start gap-2 text-sm">+ <span+ className="mt-0.5 leading-none"+ style={{ color: isBroken ? token.colorError : token.colorWarning }}+ aria-hidden+ >+ {isBroken ? <CloseCircleFilled /> : <ExclamationCircleFilled />}+ </span>++ <div>+ <div className="font-semibold">{t(reason.titleKey)}</div>+ <div>+ <span className="mr-1">+ <MonitoringTextComponent text={reason.whatHappened} />+ </span>+ <span className="text-gray-600 dark:text-gray-400">+ <MonitoringTextComponent text={reason.whatToDo} />+ </span>+ </div>+ </div>+ </li>+ );+};+export const VerdictBannerComponent = ({banner,- keepingUpSentences,+ fullBackupAction,sampledAt,now,isReducedMotion,+ onStartFullBackup,onOpenConfig,}: Props) => {const { t } = useTranslation();const { token } = theme.useToken();- const easedSentences = useEasedTransition(- keepingUpSentences,- interpolateMonitoringTexts,- isReducedMotion,- );-const toneColors = getToneColors(token, banner.tone);- const isLive =- sampledAt !== null &&- now.getTime() - new Date(sampledAt).getTime() < UNCONFIRMED_STATE_AFTER_MS;++ const measuredSeconds = sampledAt === null ? null : getSecondsBetween(sampledAt, now);+ const isLive = measuredSeconds !== null && measuredSeconds * 1000 < UNCONFIRMED_STATE_AFTER_MS;+ const isFullBackupActionShown = fullBackupAction !== FullBackupAction.HIDDEN;return (<div- className="w-full rounded-lg border p-4"+ className="w-full rounded-lg border px-4 py-3"style={{backgroundColor: toneColors.background,borderColor: toneColors.border,transition: isReducedMotion ? undefined : 'background-color 300ms, border-color 300ms',}}>- <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">- <div className="flex items-start gap-3">- <div className="text-3xl leading-none" style={{ color: toneColors.icon }} aria-hidden>- {VERDICT_ICONS[banner.icon]}- </div>+ <div className="flex min-w-0 items-start gap-2.5">+ <div className="pt-0.5 text-xl leading-none" style={{ color: toneColors.icon }} aria-hidden>+ {VERDICT_ICONS[banner.icon]}+ </div>- <div>- <div aria-live="polite" className="text-lg font-semibold">+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-0.5">+ <div aria-live="polite" className="text-base font-semibold">{t(banner.headlineKey)}</div>+ <div className="flex items-center gap-1.5 text-xs text-gray-600 dark:text-gray-400">+ <span+ aria-hidden+ className={`inline-block h-2 w-2 rounded-full ${isLive && !isReducedMotion ? 'animate-pulse' : ''}`}+ style={{ backgroundColor: isLive ? token.colorSuccess : token.colorTextQuaternary }}+ />++ {measuredSeconds === null+ ? t('backups.physical.monitoring.banner.notMeasuredYet')+ : t('backups.physical.monitoring.banner.measuredAgo', {+ duration: translateLocalizedText(getMeasurementAge(measuredSeconds), t),+ })}+ </div>+ </div>++ <div className="max-w-3xl text-sm">{banner.description && (<div className="mt-1"><MonitoringTextComponent text={banner.description} onOpenConfig={onOpenConfig} /></div>)}- {easedSentences.length > 0 && (- <div className="mt-1 text-gray-700 dark:text-gray-300">- {easedSentences.map((sentence) => (- <span key={sentence.key} className="mr-1">- <MonitoringTextComponent text={sentence} />- </span>- ))}+ {banner.headlineReason && (+ <div className="mt-1">+ <div>+ <MonitoringTextComponent text={banner.headlineReason.whatHappened} />+ </div>++ {/* The button below is the action, so its sentence would only repeat it. */}+ {!isFullBackupActionShown && (+ <div className="text-gray-600 dark:text-gray-400">+ <MonitoringTextComponent text={banner.headlineReason.whatToDo} />+ </div>+ )}</div>)}- </div>- </div>- <div className="flex shrink-0 items-center gap-2 text-sm text-gray-600 dark:text-gray-400">- <span- aria-hidden- className={`inline-block h-2.5 w-2.5 rounded-full ${isLive && !isReducedMotion ? 'animate-pulse' : ''}`}- style={{ backgroundColor: isLive ? token.colorSuccess : token.colorTextQuaternary }}- />-- {sampledAt- ? t('backups.physical.monitoring.banner.measuredAgo', {- duration: translateLocalizedText(- getMeasurementAge(getSecondsBetween(sampledAt, now)),- t,- ),- })- : t('backups.physical.monitoring.banner.notMeasuredYet')}+ <div className="mt-0.5">+ <MonitoringTextComponent text={banner.restoreSentence} />+ </div>++ {isFullBackupActionShown && (+ <Button+ className="mt-3"+ type="primary"+ loading={fullBackupAction === FullBackupAction.REQUESTING}+ onClick={onStartFullBackup}+ >+ {t('backups.physical.monitoring.banner.startFullBackup')}+ </Button>+ )}++ {banner.otherReasons.length > 0 && (+ <ul+ className="mt-3 space-y-2 border-t pt-3"+ style={{ borderColor: toneColors.border }}+ >+ {banner.otherReasons.map((reason) => (+ <OtherReasonComponent key={reason.titleKey} reason={reason} />+ ))}+ </ul>+ )}+ </div></div></div></div>diff --git a/frontend/src/features/backups/physical/monitoring/ui/WalStreamChartsComponent.tsx b/frontend/src/features/backups/physical/monitoring/ui/WalStreamChartsComponent.tsxindex 030ad397..fa974411 100644--- a/frontend/src/features/backups/physical/monitoring/ui/WalStreamChartsComponent.tsx+++ b/frontend/src/features/backups/physical/monitoring/ui/WalStreamChartsComponent.tsx@@ -1,11 +1,12 @@import { Segmented, theme } from 'antd';import dayjs from 'dayjs';+import type { ReactNode } from 'react';import { useTranslation } from 'react-i18next';import {CartesianGrid,ComposedChart,- Legend,Line,+ ReferenceArea,ReferenceLine,ResponsiveContainer,Scatter,@@ -22,38 +23,84 @@ import {import { type TranslationKey, useLocale } from '../../../../../shared/i18n';import { formatBytes } from '../../../../../shared/lib';import { useTheme } from '../../../../../shared/theme';-import { getUserTimeFormat } from '../../../../../shared/time';import { WAL_STREAM_CHART_COLORS } from '../lib/chartColors';-import { getDataSinceMs, hasAnyChartValues, toChartRows } from '../lib/chartRows';+import {+ getBinaryAxisTicks,+ getChartTimeDomain,+ getDataSinceMs,+ getMissingDataRanges,+ getRowsMaximum,+ hasEnoughChartPoints,+ toChartRows,+} from '../lib/chartRows';+import { getClockFormat } from '../lib/clockFormat';import { formatBytesPerSecond } from '../lib/monitoringTextValues';import type { WalStreamChartRow } from '../model/WalStreamChartRow';-interface Props {+interface KeepingUpChartProps {series: WalStreamSeries;period: WalStreamStatisticsPeriod;onPeriodChange: (period: WalStreamStatisticsPeriod) => void;isAnimationActive: boolean;}+interface TechnicalChartsProps {+ series: WalStreamSeries;+ walSegmentSizeBytes: number;+ isAnimationActive: boolean;+}++enum ChartLineStyle {+ SOLID = 'SOLID',+ DASHED = 'DASHED',+ // A wide translucent band under a thin line, so two equal series stay visible as a line inside+ // a band instead of one line hiding the other.+ BAND = 'BAND',+}+interface ChartLine {dataKey: keyof WalStreamChartRow;labelKey: TranslationKey;color: string;- isDashed: boolean;+ style: ChartLineStyle;+}++interface ChartMarker {+ labelKey: TranslationKey;+ color: string;+ isDiamond: boolean;}interface ChartFrameProps {titleKey: TranslationKey;subtitleKey?: TranslationKey;+ headerExtra?: ReactNode;+ heightClassName: string;rows: WalStreamChartRow[];series: WalStreamSeries;lines: ChartLine[];isRate: boolean;+ minimumTop: number;isAnimationActive: boolean;pauseLimitBytes?: number;}-const CHART_HEIGHT_PX = 220;+// The tab has a fixed maximum width, so the plots keep fixed heights that leave the rest of the tab+// on screen.+// eslint-disable-next-line i18next/no-literal-string -- Tailwind class, not copy+const MAIN_CHART_HEIGHT_CLASS = 'h-[260px]';+// eslint-disable-next-line i18next/no-literal-string -- Tailwind class, not copy+const TECHNICAL_CHART_HEIGHT_CLASS = 'h-[200px]';++const LINE_STROKE_WIDTH = 2;+const BAND_STROKE_WIDTH = 6;+const BAND_STROKE_OPACITY = 0.35;++const MAX_MISSING_DATA_CAPTIONS = 3;++// A rate below this is "almost nothing" for a database, so the rate axis never zooms in further and+// a near-idle database does not fill the chart with noise.+const RATE_AXIS_MINIMUM_TOP = 64 * 1024;// eslint-disable-next-line i18next/no-literal-string -- recharts sync group idconst CHARTS_SYNC_ID = 'walStreamMonitoring';@@ -64,21 +111,70 @@ const PERIODS = [WalStreamStatisticsPeriod.WEEK,];-/* eslint-disable i18next/no-literal-string -- dayjs format tokens, not copy */const getTimeTickFormat = (period: WalStreamStatisticsPeriod): string => {- const clockFormat = getUserTimeFormat().use12Hours ? 'h:mm A' : 'HH:mm';+ const clockFormat = getClockFormat();+ // eslint-disable-next-line i18next/no-literal-string -- dayjs format token, not copyreturn period === WalStreamStatisticsPeriod.WEEK ? `ddd ${clockFormat}` : clockFormat;};-/* eslint-enable i18next/no-literal-string */++const LegendLineSampleComponent = ({ line }: { line: ChartLine }) => (+ <svg width="24" height="10" aria-hidden className="shrink-0">+ <line+ x1="0"+ y1="5"+ x2="24"+ y2="5"+ stroke={line.color}+ strokeWidth={line.style === ChartLineStyle.BAND ? BAND_STROKE_WIDTH : LINE_STROKE_WIDTH}+ strokeOpacity={line.style === ChartLineStyle.BAND ? BAND_STROKE_OPACITY : 1}+ strokeDasharray={line.style === ChartLineStyle.DASHED ? '6 4' : undefined}+ />+ </svg>+);++const ChartLegendComponent = ({+ lines,+ markers,+}: {+ lines: ChartLine[];+ markers: ChartMarker[];+}) => {+ const { t } = useTranslation();++ return (+ <ul className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-gray-600 dark:text-gray-400">+ {lines.map((line) => (+ <li key={line.dataKey} className="flex items-center gap-1.5">+ <LegendLineSampleComponent line={line} />+ {t(line.labelKey)}+ </li>+ ))}++ {markers.map((marker) => (+ <li key={marker.labelKey} className="flex items-center gap-1.5">+ <span+ aria-hidden+ className={`inline-block h-2 w-2 shrink-0 ${marker.isDiamond ? 'rotate-45' : 'rounded-full'}`}+ style={{ backgroundColor: marker.color }}+ />+ {t(marker.labelKey)}+ </li>+ ))}+ </ul>+ );+};const ChartFrameComponent = ({titleKey,subtitleKey,+ headerExtra,+ heightClassName,rows,series,lines,isRate,+ minimumTop,isAnimationActive,pauseLimitBytes,}: ChartFrameProps) => {@@ -89,18 +185,47 @@ const ChartFrameComponent = ({const chartColors = WAL_STREAM_CHART_COLORS[resolvedTheme];const timeTickFormat = getTimeTickFormat(series.period);+ const amountTicks = getBinaryAxisTicks(+ getRowsMaximum(+ rows,+ lines.map((line) => line.dataKey),+ ),+ minimumTop,+ );+ const hasMarkers = pauseLimitBytes !== undefined;+ const markers: ChartMarker[] = hasMarkers+ ? [+ {+ labelKey: 'backups.physical.monitoring.charts.restarts',+ color: chartColors.restartMarker,+ isDiamond: false,+ },+ {+ labelKey: 'backups.physical.monitoring.charts.pauses',+ color: chartColors.pauseMarker,+ isDiamond: true,+ },+ ]+ : [];const formatAmount = (value: number) =>isRate ? formatBytesPerSecond(value, t, formatNumber) : formatBytes(value, formatNumber);return (<div>- <div className="font-semibold">{t(titleKey)}</div>- {subtitleKey && (- <div className="text-xs text-gray-600 dark:text-gray-400">{t(subtitleKey)}</div>- )}+ <div className="flex flex-wrap items-start justify-between gap-x-6 gap-y-2">+ <div className="min-w-0 space-y-1">+ <div className="font-semibold">{t(titleKey)}</div>+ {subtitleKey && (+ <div className="text-xs text-gray-600 dark:text-gray-400">{t(subtitleKey)}</div>+ )}+ <ChartLegendComponent lines={lines} markers={markers} />+ </div>++ {headerExtra}+ </div>- <div style={{ width: '100%', height: CHART_HEIGHT_PX }}>+ <div className={`mt-2 w-full ${heightClassName}`}><ResponsiveContainer width="100%" height="100%"><ComposedChartdata={rows}@@ -112,13 +237,16 @@ const ChartFrameComponent = ({dataKey="timestampMs"type="number"scale="time"- domain={[new Date(series.from).getTime(), new Date(series.to).getTime()]}+ domain={getChartTimeDomain(series)}+ allowDataOverflowtickFormatter={(timestampMs: number) => dayjs(timestampMs).format(timeTickFormat)}tick={{ fontSize: 11, fill: token.colorTextSecondary }}stroke={token.colorBorder}/><YAxiswidth={80}+ domain={[0, amountTicks[amountTicks.length - 1]]}+ ticks={amountTicks}tickFormatter={formatAmount}tick={{ fontSize: 11, fill: token.colorTextSecondary }}stroke={token.colorBorder}@@ -132,7 +260,17 @@ const ChartFrameComponent = ({labelFormatter={(timestampMs) => dayjs(Number(timestampMs)).format(timeTickFormat)}formatter={(value) => (typeof value === 'number' ? formatAmount(value) : value)}/>- <Legend verticalAlign="top" height={28} wrapperStyle={{ fontSize: 12 }} />++ {getMissingDataRanges(series).map((range) => (+ <ReferenceArea+ key={range.fromMs}+ x1={range.fromMs}+ x2={range.toMs}+ fill={token.colorFillSecondary}+ fillOpacity={1}+ ifOverflow="hidden"+ />+ ))}{lines.map((line) => (<Line@@ -141,15 +279,18 @@ const ChartFrameComponent = ({dataKey={line.dataKey}name={t(line.labelKey)}stroke={line.color}- strokeWidth={2}- strokeDasharray={line.isDashed ? '6 4' : undefined}+ strokeWidth={+ line.style === ChartLineStyle.BAND ? BAND_STROKE_WIDTH : LINE_STROKE_WIDTH+ }+ strokeOpacity={line.style === ChartLineStyle.BAND ? BAND_STROKE_OPACITY : 1}+ strokeDasharray={line.style === ChartLineStyle.DASHED ? '6 4' : undefined}dot={false}connectNulls={false}isAnimationActive={isAnimationActive}/>))}- {pauseLimitBytes !== undefined && (+ {hasMarkers && (<ReferenceLiney={pauseLimitBytes}stroke={chartColors.pauseLimit}@@ -163,7 +304,7 @@ const ChartFrameComponent = ({/>)}- {pauseLimitBytes !== undefined && (+ {hasMarkers && (<ScatterdataKey="restartMarkerBytes"name={t('backups.physical.monitoring.charts.restarts')}@@ -172,7 +313,7 @@ const ChartFrameComponent = ({/>)}- {pauseLimitBytes !== undefined && (+ {hasMarkers && (<ScatterdataKey="pauseMarkerBytes"name={t('backups.physical.monitoring.charts.pauses')}@@ -188,110 +329,184 @@ const ChartFrameComponent = ({);};-export const WalStreamChartsComponent = ({+// A chart drawn from a handful of points says nothing, so until enough data exists the reader gets+// an explanation instead.+export const ChartAvailabilityComponent = ({series,- period,- onPeriodChange,- isAnimationActive,-}: Props) => {+ children,+}: {+ series: WalStreamSeries;+ children: ReactNode;+}) => {const { t } = useTranslation();- const { resolvedTheme } = useTheme();- const chartColors = WAL_STREAM_CHART_COLORS[resolvedTheme];- const rows = toChartRows(series.points);+ if (!hasEnoughChartPoints(series)) {+ return (+ <div className="mt-4 rounded-lg border border-dashed border-gray-300 p-6 text-center text-gray-600 dark:border-gray-600 dark:text-gray-400">+ {t('backups.physical.monitoring.charts.notEnoughData')}+ </div>+ );+ }+const dataSinceMs = getDataSinceMs(series);- const latestPauseLimitBytes = [...series.points]- .reverse()- .find((point) => point.localQueuePauseBytes !== null)?.localQueuePauseBytes;+ const missingDataRanges = getMissingDataRanges(series).slice(0, MAX_MISSING_DATA_CAPTIONS);+ const timeFormat = getTimeTickFormat(series.period);return (- <div className="mt-6">- <Segmented- value={period}- onChange={(value) => onPeriodChange(value as WalStreamStatisticsPeriod)}- options={PERIODS.map((periodOption) => ({- value: periodOption,- label: t(WAL_STREAM_STATISTICS_PERIOD_LABEL_KEYS[periodOption]),- }))}- />+ <div className="mt-4 space-y-6">+ {children}- {!hasAnyChartValues(series) ? (- <div className="mt-4 rounded-lg border border-dashed border-gray-300 p-6 text-center text-gray-600 dark:border-gray-600 dark:text-gray-400">- {t('backups.physical.monitoring.charts.noHistory')}- </div>- ) : (- <div className="mt-4 space-y-6">+ {(dataSinceMs !== null || missingDataRanges.length > 0) && (+ <div className="space-y-0.5 text-xs text-gray-600 dark:text-gray-400">{dataSinceMs !== null && (- <div className="text-xs text-gray-600 dark:text-gray-400">+ <div>{t('backups.physical.monitoring.charts.dataSince', {- time: dayjs(dataSinceMs).format(getTimeTickFormat(series.period)),+ time: dayjs(dataSinceMs).format(timeFormat),})}</div>)}- <ChartFrameComponent- titleKey="backups.physical.monitoring.charts.keepingUpTitle"- rows={rows}- series={series}- isRate- isAnimationActive={isAnimationActive}- lines={[- {- dataKey: 'sourceWriteBytesPerSecond',- labelKey: 'backups.physical.monitoring.charts.databaseWrites',- color: chartColors.sourceWrites,- isDashed: false,- },- {- dataKey: 'archiveBytesPerSecond',- labelKey: 'backups.physical.monitoring.charts.savedToStorage',- color: chartColors.archive,- isDashed: true,- },- ]}- />+ {missingDataRanges.map((range) => (+ <div key={range.fromMs}>+ {t('backups.physical.monitoring.charts.noMeasurements', {+ from: dayjs(range.fromMs).format(timeFormat),+ to: dayjs(range.toMs).format(timeFormat),+ })}+ </div>+ ))}+ </div>+ )}+ </div>+ );+};- <ChartFrameComponent- titleKey="backups.physical.monitoring.charts.unsavedTitle"- subtitleKey="backups.physical.monitoring.charts.unsavedSubtitle"- rows={rows}- series={series}- isRate={false}- isAnimationActive={isAnimationActive}- lines={[- {- dataKey: 'maxUnarchivedWalBytes',- labelKey: 'backups.physical.monitoring.charts.notSavedYet',- color: chartColors.notSavedYet,- isDashed: false,- },- {- dataKey: 'maxSlotLagBytes',- labelKey: 'backups.physical.monitoring.charts.notReceivedYet',- color: chartColors.notReceivedYet,- isDashed: true,- },- ]}- />+export const WalStreamKeepingUpChartComponent = ({+ series,+ period,+ onPeriodChange,+ isAnimationActive,+}: KeepingUpChartProps) => {+ const { t } = useTranslation();+ const { resolvedTheme } = useTheme();- <ChartFrameComponent- titleKey="backups.physical.monitoring.charts.bufferTitle"- rows={rows}- series={series}- isRate={false}- isAnimationActive={isAnimationActive}- pauseLimitBytes={latestPauseLimitBytes ?? 0}- lines={[- {- dataKey: 'maxLocalQueueBytes',- labelKey: 'backups.physical.monitoring.charts.waitingInBuffer',- color: chartColors.buffer,- isDashed: false,- },- ]}- />+ const chartColors = WAL_STREAM_CHART_COLORS[resolvedTheme];++ const periodSwitch = (+ <Segmented+ value={period}+ onChange={(value) => onPeriodChange(value as WalStreamStatisticsPeriod)}+ options={PERIODS.map((periodOption) => ({+ value: periodOption,+ label: t(WAL_STREAM_STATISTICS_PERIOD_LABEL_KEYS[periodOption]),+ }))}+ />+ );++ if (!hasEnoughChartPoints(series)) {+ return (+ <div className="mt-6">+ <div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-2">+ <div className="font-semibold">+ {t('backups.physical.monitoring.charts.keepingUpTitle')}+ </div>+ {periodSwitch}</div>- )}++ <ChartAvailabilityComponent series={series}>{null}</ChartAvailabilityComponent>+ </div>+ );+ }++ return (+ <div className="mt-6">+ <ChartAvailabilityComponent series={series}>+ <ChartFrameComponent+ titleKey="backups.physical.monitoring.charts.keepingUpTitle"+ headerExtra={periodSwitch}+ heightClassName={MAIN_CHART_HEIGHT_CLASS}+ rows={toChartRows(series.points)}+ series={series}+ isRate+ minimumTop={RATE_AXIS_MINIMUM_TOP}+ isAnimationActive={isAnimationActive}+ lines={[+ {+ dataKey: 'archiveBytesPerSecond',+ labelKey: 'backups.physical.monitoring.charts.savedToStorage',+ color: chartColors.archive,+ style: ChartLineStyle.BAND,+ },+ {+ dataKey: 'sourceWriteBytesPerSecond',+ labelKey: 'backups.physical.monitoring.charts.databaseWrites',+ color: chartColors.sourceWrites,+ style: ChartLineStyle.SOLID,+ },+ ]}+ />+ </ChartAvailabilityComponent></div>);};++export const WalStreamTechnicalChartsComponent = ({+ series,+ walSegmentSizeBytes,+ isAnimationActive,+}: TechnicalChartsProps) => {+ const { resolvedTheme } = useTheme();++ const chartColors = WAL_STREAM_CHART_COLORS[resolvedTheme];+ const rows = toChartRows(series.points);+ const latestPauseLimitBytes =+ [...series.points].reverse().find((point) => point.localQueuePauseBytes !== null)+ ?.localQueuePauseBytes ?? 0;++ return (+ <ChartAvailabilityComponent series={series}>+ <ChartFrameComponent+ titleKey="backups.physical.monitoring.charts.unsavedTitle"+ subtitleKey="backups.physical.monitoring.charts.unsavedSubtitle"+ heightClassName={TECHNICAL_CHART_HEIGHT_CLASS}+ rows={rows}+ series={series}+ isRate={false}+ minimumTop={walSegmentSizeBytes}+ isAnimationActive={isAnimationActive}+ lines={[+ {+ dataKey: 'maxUnarchivedWalBytes',+ labelKey: 'backups.physical.monitoring.charts.notSavedYet',+ color: chartColors.notSavedYet,+ style: ChartLineStyle.SOLID,+ },+ {+ dataKey: 'maxSlotLagBytes',+ labelKey: 'backups.physical.monitoring.charts.notReceivedYet',+ color: chartColors.notReceivedYet,+ style: ChartLineStyle.DASHED,+ },+ ]}+ />++ <ChartFrameComponent+ titleKey="backups.physical.monitoring.charts.bufferTitle"+ heightClassName={TECHNICAL_CHART_HEIGHT_CLASS}+ rows={rows}+ series={series}+ isRate={false}+ minimumTop={Math.max(walSegmentSizeBytes, latestPauseLimitBytes)}+ isAnimationActive={isAnimationActive}+ pauseLimitBytes={latestPauseLimitBytes}+ lines={[+ {+ dataKey: 'maxLocalQueueBytes',+ labelKey: 'backups.physical.monitoring.charts.waitingInBuffer',+ color: chartColors.buffer,+ style: ChartLineStyle.SOLID,+ },+ ]}+ />+ </ChartAvailabilityComponent>+ );+};diff --git a/frontend/src/features/backups/physical/monitoring/ui/WalStreamMonitoringComponent.tsx b/frontend/src/features/backups/physical/monitoring/ui/WalStreamMonitoringComponent.tsxindex ae3091ca..445027a8 100644--- a/frontend/src/features/backups/physical/monitoring/ui/WalStreamMonitoringComponent.tsx+++ b/frontend/src/features/backups/physical/monitoring/ui/WalStreamMonitoringComponent.tsx@@ -1,34 +1,41 @@-import { Alert, Button, Skeleton } from 'antd';+import { Alert, App, Button, Skeleton } from 'antd';import { type ReactNode, memo, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import {- WalStreamHealthLevel,+ type WalStreamLive,WalStreamStatisticsPeriod,+ physicalBackupsApi,physicalWalStreamStatisticsApi,} from '../../../../../entity/backups/physical';import type { Database } from '../../../../../entity/databases';import { translateApiError } from '../../../../../shared/i18n';+import { getFullBackupAction } from '../lib/fullBackupAction';+import { FullBackupRequestController } from '../lib/fullBackupRequestController';import { getKeepingUpSentences } from '../lib/keepingUpSentences';+import { applyLiveValues } from '../lib/liveOverlay';+import { getMonitoringFigures } from '../lib/monitoringFigures';import { getStageTones } from '../lib/pathStages';-import { getNoticeTexts, getReasonTexts, sortReasonsBrokenFirst } from '../lib/reasonTexts';+import { getTipTexts } from '../lib/reasonTexts';import { getVerdictBanner } from '../lib/verdictBanner';+import { WalStreamLiveController } from '../lib/walStreamLiveController';import {type PageVisibility,type RefreshTimer,WalStreamRefreshController,} from '../lib/walStreamRefreshController';import type { WalStreamRefreshState } from '../model/WalStreamRefreshState';-import { ChangesPathComponent } from './ChangesPathComponent';-import { MonitoringReasonsComponent } from './MonitoringReasonsComponent';+import { MonitoringFiguresComponent } from './MonitoringFiguresComponent';+import { RestoreTimelineComponent } from './RestoreTimelineComponent';+import { TechnicalDetailsComponent } from './TechnicalDetailsComponent';import { useCurrentTime } from './useCurrentTime';import { usePrefersReducedMotion } from './usePrefersReducedMotion';import { VerdictBannerComponent } from './VerdictBannerComponent';-import { WalStreamChartsComponent } from './WalStreamChartsComponent';-import { WalStreamDetailsComponent } from './WalStreamDetailsComponent';+import { WalStreamKeepingUpChartComponent } from './WalStreamChartsComponent';interface Props {database: Database;+ isCanManageDBs: boolean;isDirectlyUnderTab: boolean;onOpenConfig: () => void;}@@ -55,7 +62,7 @@ const browserRefreshTimer: RefreshTimer = {const CHART_ENTRY_ANIMATION_MS = 1500;// The charts re-render only when a refresh brings a new series, not on every tick of the clock.-const MemoizedWalStreamChartsComponent = memo(WalStreamChartsComponent);+const MemoizedWalStreamKeepingUpChartComponent = memo(WalStreamKeepingUpChartComponent);const MonitoringContainerComponent = ({isDirectlyUnderTab,@@ -64,8 +71,10 @@ const MonitoringContainerComponent = ({isDirectlyUnderTab: boolean;children: ReactNode;}) => (+ // The width stops where a line of text and a chart still read at a glance; past it the tab only+ // grows empty space.<div- className={`w-full bg-white p-3 shadow md:p-5 dark:bg-gray-800 ${isDirectlyUnderTab ? 'rounded-tr-md rounded-br-md rounded-bl-md' : 'rounded-md'}`}+ className={`w-full max-w-6xl bg-white p-3 shadow md:p-5 dark:bg-gray-800 ${isDirectlyUnderTab ? 'rounded-tr-md rounded-br-md rounded-bl-md' : 'rounded-md'}`}>{children}</div>@@ -87,23 +96,32 @@ const MonitoringSkeletonComponent = () => (export const WalStreamMonitoringComponent = ({database,+ isCanManageDBs,isDirectlyUnderTab,onOpenConfig,}: Props) => {const { t } = useTranslation();+ const { message } = App.useApp();const [period, setPeriod] = useState(WalStreamStatisticsPeriod.HOUR);const [refreshState, setRefreshState] = useState<WalStreamRefreshState | null>(null);const [lastAnimatedPeriod, setLastAnimatedPeriod] = useState<WalStreamStatisticsPeriod | null>(null,);+ const [isRequestingFullBackup, setIsRequestingFullBackup] = useState(false);+ const [live, setLive] = useState<WalStreamLive | null>(null);const controllerRef = useRef<WalStreamRefreshController | null>(null);+ const fullBackupRequestControllerRef = useRef<FullBackupRequestController | null>(null);const retryFirstLoad = () => {controllerRef.current?.retry();};+ const startFullBackup = () => {+ void fullBackupRequestControllerRef.current?.requestFullBackup();+ };+const now = useCurrentTime();const isReducedMotion = usePrefersReducedMotion();@@ -131,6 +149,40 @@ export const WalStreamMonitoringComponent = ({return () => controller.stop();}, [database.id]);+ useEffect(() => {+ setLive(null);++ const liveController = new WalStreamLiveController(+ {+ fetchLive: () => physicalWalStreamStatisticsApi.getWalStreamLive(database.id),+ timer: browserRefreshTimer,+ pageVisibility: browserPageVisibility,+ },+ setLive,+ );++ liveController.start();++ return () => liveController.stop();+ }, [database.id]);++ useEffect(() => {+ fullBackupRequestControllerRef.current = new FullBackupRequestController(+ {+ requestFullBackup: () => physicalBackupsApi.triggerPhysicalBackup(database.id, 'full'),+ refreshNow: () => controllerRef.current?.retry(),+ reportRequested: () =>+ message.success(t('backups.physical.monitoring.banner.fullBackupRequested')),+ reportError: (e) => message.error(translateApiError(e, t)),+ },+ setIsRequestingFullBackup,+ );+ }, [database.id, message, t]);++ useEffect(() => {+ fullBackupRequestControllerRef.current?.handleRefreshLanded();+ }, [refreshState]);+const shownSeriesPeriod = refreshState?.statistics?.series.period ?? null;useEffect(() => {@@ -146,7 +198,9 @@ export const WalStreamMonitoringComponent = ({return () => clearTimeout(timeout);}, [shownSeriesPeriod, lastAnimatedPeriod]);- const statistics = refreshState?.statistics ?? null;+ const statistics = refreshState?.statistics+ ? applyLiveValues(refreshState.statistics, live)+ : null;if (!statistics || !refreshState?.lastSuccessfulRefreshAt) {return (@@ -169,32 +223,32 @@ export const WalStreamMonitoringComponent = ({);}- const { health } = statistics;- const banner = getVerdictBanner(health.level, refreshState.lastSuccessfulRefreshAt, now);- const isVerdictAboutStreaming =- health.level !== WalStreamHealthLevel.NOT_STREAMING &&- health.level !== WalStreamHealthLevel.COLLECTING_DATA;-- const reasons = sortReasonsBrokenFirst(health.reasons).map((reason) =>- getReasonTexts(reason, health.isFullBackupPending, now),- );- const notices = health.notices.map((notice) => ({- code: notice.code,- texts: getNoticeTexts(notice),- }));+ const banner = getVerdictBanner({+ statistics,+ lastSuccessfulRefreshAt: refreshState.lastSuccessfulRefreshAt,+ now,+ });+ const figures = getMonitoringFigures(statistics);+ const isChartAnimationActive =+ !isReducedMotion && statistics.series.period !== lastAnimatedPeriod;return (<MonitoringContainerComponent isDirectlyUnderTab={isDirectlyUnderTab}><VerdictBannerComponentbanner={banner}- keepingUpSentences={- banner.isStateConfirmed && isVerdictAboutStreaming- ? getKeepingUpSentences(statistics.keepingUp)- : []- }+ fullBackupAction={getFullBackupAction({+ level: statistics.health.level,+ isStateConfirmed: banner.isStateConfirmed,+ reasons: statistics.health.reasons,+ latestRestorableAt: statistics.latestRestorableAt,+ isFullBackupPending: statistics.health.isFullBackupPending,+ isCanManageDBs,+ isRequestingFullBackup,+ })}sampledAt={statistics.current?.sampledAt ?? null}now={now}isReducedMotion={isReducedMotion}+ onStartFullBackup={startFullBackup}onOpenConfig={onOpenConfig}/>@@ -207,22 +261,30 @@ export const WalStreamMonitoringComponent = ({/>)}- <MonitoringReasonsComponent reasons={reasons} notices={notices} />+ {figures && (+ <MonitoringFiguresComponent+ figures={figures}+ keepingUpSentences={getKeepingUpSentences(statistics.keepingUp)}+ isReducedMotion={isReducedMotion}+ />+ )}- <ChangesPathComponent- statistics={statistics}- stageTones={getStageTones(health.level, health.reasons)}- isReducedMotion={isReducedMotion}- />+ <RestoreTimelineComponent ranges={statistics.restorableRanges} now={now} />- <MemoizedWalStreamChartsComponent+ <MemoizedWalStreamKeepingUpChartComponentseries={statistics.series}period={period}onPeriodChange={changePeriod}- isAnimationActive={!isReducedMotion && statistics.series.period !== lastAnimatedPeriod}+ isAnimationActive={isChartAnimationActive}/>- <WalStreamDetailsComponent statistics={statistics} />+ <TechnicalDetailsComponent+ statistics={statistics}+ stageTones={getStageTones(statistics.health.level, statistics.health.reasons)}+ tips={getTipTexts(statistics.health.notices)}+ isReducedMotion={isReducedMotion}+ isChartAnimationActive={isChartAnimationActive}+ /></MonitoringContainerComponent>);};diff --git a/frontend/src/features/backups/physical/monitoring/ui/WalStreamMonitoringSections.test.tsx b/frontend/src/features/backups/physical/monitoring/ui/WalStreamMonitoringSections.test.tsxindex 0da08911..aaa94e0a 100644--- a/frontend/src/features/backups/physical/monitoring/ui/WalStreamMonitoringSections.test.tsx+++ b/frontend/src/features/backups/physical/monitoring/ui/WalStreamMonitoringSections.test.tsx@@ -3,150 +3,306 @@ import { renderToStaticMarkup } from 'react-dom/server';import { describe, expect, it, vi } from 'vitest';import {+ type WalStreamHealth,WalStreamHealthLevel,WalStreamKeepingUpState,WalStreamNoticeCode,WalStreamReasonCode,WalStreamReasonLevel,- WalStreamSourceState,+ type WalStreamSeriesPoint,type WalStreamStatistics,- WalStreamStatisticsPeriod,- WalStreamStreamerState,} from '../../../../../entity/backups/physical';import { LocaleProvider } from '../../../../../shared/i18n';-import { getKeepingUpSentences } from '../lib/keepingUpSentences';+import { ThemeContext } from '../../../../../shared/theme';+import { getFullBackupAction } from '../lib/fullBackupAction';+import { getMonitoringFigures } from '../lib/monitoringFigures';import { getStageTones } from '../lib/pathStages';-import { getNoticeTexts, getReasonTexts } from '../lib/reasonTexts';+import { getTipTexts } from '../lib/reasonTexts';+import { createTestWalStreamStatistics } from '../lib/testWalStreamStatistics';import { getVerdictBanner } from '../lib/verdictBanner';import { ChangesPathComponent } from './ChangesPathComponent';-import { MonitoringReasonsComponent } from './MonitoringReasonsComponent';+import { MonitoringFiguresComponent } from './MonitoringFiguresComponent';+import { RestoreTimelineComponent } from './RestoreTimelineComponent';+import { TechnicalDetailsComponent } from './TechnicalDetailsComponent';import { VerdictBannerComponent } from './VerdictBannerComponent';-import { WalStreamDetailsComponent } from './WalStreamDetailsComponent';+import { ChartAvailabilityComponent } from './WalStreamChartsComponent';// The entity's public API imports its API client, and the client's config module reads window at// import time. The tests run in node, so they supply window. LocaleProvider then reads-// localStorage, which here reports no saved language.+// localStorage, which here reports no saved language. Times render in the local zone, so the+// tests pin it.vi.hoisted(() => {vi.stubGlobal('window', {});vi.stubGlobal('localStorage', { getItem: () => null });vi.stubGlobal('navigator', { language: 'en-US', languages: ['en-US'] });+ vi.stubEnv('TZ', 'UTC');});const MiB = 1024 * 1024;const now = new Date('2026-10-18T12:00:00Z');-const statistics: WalStreamStatistics = {- health: {- level: WalStreamHealthLevel.NEEDS_ATTENTION,- reasons: [- {- code: WalStreamReasonCode.LOCAL_QUEUE_FILLING,- level: WalStreamReasonLevel.NEEDS_ATTENTION,- valueBytes: 600 * MiB,- thresholdBytes: 512 * MiB,- },- ],- notices: [{ code: WalStreamNoticeCode.NO_SLOT_WAL_LIMIT, level: WalStreamReasonLevel.INFO }],- isFullBackupPending: false,- },- streamer: {- state: WalStreamStreamerState.RUNNING,- sessionStartedAt: '2026-10-18T10:00:00Z',- failingSince: null,- restartsLastHour: 1,- },- current: {- sampledAt: '2026-10-18T11:59:48Z',- lastArchivedWalAt: '2026-10-18T11:59:20Z',- sessionStartedAt: '2026-10-18T10:00:00Z',- sourceState: WalStreamSourceState.REACHABLE,- sourceUnreachableSince: null,- sourceCurrentLsn: '0/5000000',- archiveProgressLsn: '0/4F00000',- sourceWrittenBytes: 16 * MiB,- archivedSegments: 2,- archivedWalBytes: 32 * MiB,- archivedStoredBytes: 8 * MiB,- walSegmentSizeBytes: 16 * MiB,- highestConcurrentUploads: 3,- segmentWriteAvgMillis: 120,- segmentWriteMaxMillis: 300,- slotWalStatus: 'reserved',- slotExtraWalSince: null,- slotLagBytes: 2 * MiB,- slotSafeWalSizeBytes: null,- unarchivedWalBytes: 24 * MiB,- archiveStalledSince: null,- localQueueBytes: 600 * MiB,- localQueuePauseBytes: 512 * MiB,- receiverRestarts: 0,- receiverPauses: 0,- isReceiverRunning: false,- isForcedRotationDenied: false,- },- keepingUp: {- state: WalStreamKeepingUpState.KEEPING_UP,- sourceWriteBytesPerSecond: 10 * MiB,- archiveBytesPerSecond: 10 * MiB,- unarchivedWalBytes: 24 * MiB,- unarchivedWalChangeBytesPerSecond: 0,- slotLagBytes: 2 * MiB,- slotLagChangeBytesPerSecond: 0,- slotRebuildLagBytes: 256 * MiB,- estimatedCatchUpSeconds: null,- estimatedSlotRebuildSeconds: null,- estimatedSlotLimitSeconds: null,- },- series: {- period: WalStreamStatisticsPeriod.HOUR,- bucketSeconds: 60,- from: '2026-10-18T11:01:00Z',- to: '2026-10-18T12:01:00Z',- points: [],- },+const brokenChainHealth: WalStreamHealth = {+ level: WalStreamHealthLevel.BROKEN,+ reasons: [+ { code: WalStreamReasonCode.WAL_CHAIN_BROKEN, level: WalStreamReasonLevel.BROKEN },+ {+ code: WalStreamReasonCode.LOCAL_QUEUE_FILLING,+ level: WalStreamReasonLevel.NEEDS_ATTENTION,+ valueBytes: 600 * MiB,+ thresholdBytes: 512 * MiB,+ },+ ],+ notices: [],+ isFullBackupPending: false,};+const buildPoint = (minute: number, hasValues: boolean): WalStreamSeriesPoint => ({+ startedAt: new Date(Date.parse('2026-10-18T11:01:00Z') + minute * 60_000).toISOString(),+ sourceWriteBytesPerSecond: hasValues ? 10 * MiB : null,+ archiveBytesPerSecond: hasValues ? 10 * MiB : null,+ archivedStoredBytesPerSecond: hasValues ? 3 * MiB : null,+ maxSlotLagBytes: hasValues ? 2 * MiB : null,+ maxUnarchivedWalBytes: hasValues ? 20 * MiB : null,+ maxLocalQueueBytes: hasValues ? 0 : null,+ localQueuePauseBytes: hasValues ? 512 * MiB : null,+ restarts: hasValues ? 0 : null,+ pauses: hasValues ? 0 : null,+ sessionStarts: hasValues ? 0 : null,+ highestConcurrentUploads: hasValues ? 2 : null,+ segmentWriteAvgMillis: hasValues ? 100 : null,+ segmentWriteMaxMillis: hasValues ? 200 : null,+});++// Values only for the last 20 minutes of the hour.+const buildSeriesStartingInsidePeriod = (): WalStreamStatistics['series'] => ({+ ...createTestWalStreamStatistics().series,+ points: Array.from({ length: 60 }, (_, minute) => buildPoint(minute, minute >= 40)),+});+const renderWithLocale = (element: JSX.Element) =>- renderToStaticMarkup(<LocaleProvider>{element}</LocaleProvider>);+ renderToStaticMarkup(+ <ThemeContext.Provider value={{ theme: 'light', resolvedTheme: 'light', setTheme: () => {} }}>+ <LocaleProvider>{element}</LocaleProvider>+ </ThemeContext.Provider>,+ );++const renderBanner = (statistics: WalStreamStatistics, isCanManageDBs: boolean) => {+ const banner = getVerdictBanner({ statistics, lastSuccessfulRefreshAt: now, now });++ return renderWithLocale(+ <VerdictBannerComponent+ banner={banner}+ fullBackupAction={getFullBackupAction({+ level: statistics.health.level,+ isStateConfirmed: banner.isStateConfirmed,+ reasons: statistics.health.reasons,+ latestRestorableAt: statistics.latestRestorableAt,+ isFullBackupPending: statistics.health.isFullBackupPending,+ isCanManageDBs,+ isRequestingFullBackup: false,+ })}+ sampledAt={statistics.current?.sampledAt ?? null}+ now={now}+ isReducedMotion+ onStartFullBackup={() => {}}+ onOpenConfig={() => {}}+ />,+ );+};++const getBrokenChainStatistics = (): WalStreamStatistics => {+ const statistics = createTestWalStreamStatistics({+ health: brokenChainHealth,+ latestRestorableAt: '2026-10-18T07:50:00Z',+ });++ return {+ ...statistics,+ current: statistics.current && {+ ...statistics.current,+ lastArchivedWalAt: '2026-10-18T11:59:20Z',+ },+ };+};describe('the Monitoring tab sections', () => {- it('leads with the verdict, the keeping-up sentence and the age of the newest sample', () => {+ it('says that all changes are saved and to which moment the database can be restored', () => {+ const markup = renderBanner(createTestWalStreamStatistics(), true);++ expect(markup).toContain('All changes are being saved');+ expect(markup).toContain('aria-live="polite"');+ expect(markup).toContain(+ 'You can restore the database to any moment up to 11:59 AM (40 s ago).',+ );+ expect(markup).toContain('Measured 12 s ago');+ expect(markup).toMatch(+ /font-semibold">All changes are being saved<\/div><div[^>]*>.*Measured 12 s ago/,+ );+ expect(markup).not.toContain('Start full backup');+ expect(markup).not.toContain('writes almost nothing');+ });++ it('names a broken chain in the headline, limits the restore to the moment before it and offers a full backup instead of the sentence', () => {+ const markup = renderBanner(getBrokenChainStatistics(), true);++ expect(markup).toContain('Changes were lost between backups');+ expect(markup).toContain('Part of the change history never reached storage');+ expect(markup).not.toContain('Start a full backup on the Backups tab.');+ expect(markup).toContain(+ 'Until a new full backup finishes, you can restore the database only up to 7:50 AM',+ );+ expect(markup).toContain('Start full backup');+ expect(markup).toContain('The Databasus buffer is filling up');+ expect(markup).toContain('The Databasus buffer holds 600 MB of 512 MB.');+ });++ it('shows the problem without the full backup button to a user who cannot manage the database', () => {+ const markup = renderBanner(getBrokenChainStatistics(), false);++ expect(markup).toContain('Changes were lost between backups');+ expect(markup).toContain('Start a full backup on the Backups tab.');+ expect(markup).not.toContain('Start full backup');+ });++ it('shows the three figures and says not measured instead of zero for unknown rates', () => {+ const statistics = createTestWalStreamStatistics();+ const figures = getMonitoringFigures({+ ...statistics,+ keepingUp: {+ ...statistics.keepingUp,+ state: WalStreamKeepingUpState.UNKNOWN,+ sourceWriteBytesPerSecond: null,+ archiveBytesPerSecond: null,+ },+ });++ const markup = renderWithLocale(+ <MonitoringFiguresComponent figures={figures!} keepingUpSentences={[]} isReducedMotion />,+ );++ expect(markup).toContain('Last change saved');+ expect(markup).toContain('Waiting to be saved');+ expect(markup).toContain('Database writes');+ expect(markup).toContain('Saved to storage');+ expect(markup).toContain('20 MB');+ expect(markup.match(/Not measured yet/g)).toHaveLength(2);+ expect(markup).not.toContain('0 B/s');+ });++ it('shows each rate as its own card, marked as a 10-minute average, next to the other figures', () => {+ const statistics = createTestWalStreamStatistics();+const markup = renderWithLocale(- <VerdictBannerComponent- banner={getVerdictBanner(statistics.health.level, now, now)}- keepingUpSentences={getKeepingUpSentences(statistics.keepingUp)}- sampledAt={statistics.current?.sampledAt ?? null}+ <MonitoringFiguresComponent+ figures={getMonitoringFigures(statistics)!}+ keepingUpSentences={[]}+ isReducedMotion+ />,+ );++ expect(markup.match(/rounded-lg border/g)).toHaveLength(4);+ expect(markup).toContain('10 MB/s');+ expect(markup.match(/avg\. 10 min/g)).toHaveLength(2);+ });++ it('marks a gap an incremental backup bridged on the restore timeline and says it in words', () => {+ const markup = renderWithLocale(+ <RestoreTimelineComponent+ ranges={[+ { from: '2026-10-10T12:00:00Z', to: '2026-10-10T18:35:00Z' },+ { from: '2026-10-18T07:51:00Z', to: '2026-10-18T11:59:20Z' },+ ]}now={now}+ />,+ );++ expect(markup).toContain('What you can restore');+ expect(markup).toContain('Cannot be restored');+ expect(markup).toMatch(+ /You cannot restore the database to moments between .*6:35 PM and 7:51 AM: these changes never reached storage\./,+ );+ });++ it('shows no restore timeline before the first full backup', () => {+ expect(renderWithLocale(<RestoreTimelineComponent ranges={[]} now={now} />)).toBe('');+ });++ it('shows each tip with its title and both sentences inside the technical details', () => {+ const statistics = createTestWalStreamStatistics();++ const markup = renderWithLocale(+ <TechnicalDetailsComponent+ statistics={statistics}+ stageTones={getStageTones(statistics.health.level, statistics.health.reasons)}+ tips={getTipTexts([+ { code: WalStreamNoticeCode.NO_SLOT_WAL_LIMIT, level: WalStreamReasonLevel.INFO },+ ])}isReducedMotion- onOpenConfig={() => {}}+ isChartAnimationActive={false}/>,);- expect(markup).toContain('Something needs attention');- expect(markup).toContain('aria-live="polite"');+ expect(markup).toContain('<div class="font-semibold">No limit on kept changes</div>');+ expect(markup).toContain('The database keeps changes for Databasus without a limit.');+ expect(markup).toContain('A limit protects the database server');+ expect(markup).toContain('max_slot_wal_keep_size');+ });++ it('shows the path of changes, both extra charts and the raw values without a click', () => {+ const statistics = createTestWalStreamStatistics({+ series: buildSeriesStartingInsidePeriod(),+ });++ const markup = renderWithLocale(+ <TechnicalDetailsComponent+ statistics={statistics}+ stageTones={getStageTones(statistics.health.level, statistics.health.reasons)}+ tips={[]}+ isReducedMotion+ isChartAnimationActive={false}+ />,+ );++ expect(markup).toContain('Technical details');+ expect(markup).toContain('Not received by Databasus yet');+ expect(markup).toContain('Waiting in the buffer');+ expect(markup).toContain('How much is not saved yet?');+ expect(markup).toContain('Databasus buffer');+ expect(markup).toContain('Slot status (wal_status)');+ });++ it('says that there is not enough data instead of drawing a chart from a few points', () => {+ const series = {+ ...createTestWalStreamStatistics().series,+ points: [buildPoint(0, true), buildPoint(1, true)],+ };++ const markup = renderWithLocale(+ <ChartAvailabilityComponent series={series}>+ <div>chart</div>+ </ChartAvailabilityComponent>,+ );+expect(markup).toContain(- 'Databasus saves changes as fast as the database writes them: 10 MB/s written',+ 'Not enough data for this period yet. A shorter period may already have a chart.',);- expect(markup).toContain('Measured 12 s ago');+ expect(markup).not.toContain('chart</div>');});- it('lists each reason with what happened and what to do, and names the setting in the notice', () => {+ it('says since when it has data when the data starts inside the period', () => {const markup = renderWithLocale(- <MonitoringReasonsComponent- reasons={statistics.health.reasons.map((reason) => getReasonTexts(reason, false, now))}- notices={statistics.health.notices.map((notice) => ({- code: notice.code,- texts: getNoticeTexts(notice),- }))}- />,+ <ChartAvailabilityComponent series={buildSeriesStartingInsidePeriod()}>+ <div>chart</div>+ </ChartAvailabilityComponent>,);- expect(markup).toContain('The Databasus buffer is filling up');- expect(markup).toContain('The Databasus buffer holds 600 MB of 512 MB.');- expect(markup).toContain('No limit on kept changes');+ expect(markup).toContain('Data since 11:41 AM');+ expect(markup).toContain('chart</div>');});- it('shows an amount above its limit as over the limit and the receiver as paused', () => {+ it('draws a healthy path without problem marks, says nothing waits in an empty queue and how much of a limit a filled one uses', () => {+ const statistics = createTestWalStreamStatistics();+const markup = renderWithLocale(<ChangesPathComponentstatistics={statistics}@@ -155,16 +311,82 @@ describe('the Monitoring tab sections', () => {/>,);- expect(markup).toContain('Over the limit');- expect(markup).toContain('Receiving paused');- expect(markup).toContain('Receiving pauses at 512 MB');- expect(markup).toContain('No limit on kept changes');+ expect(markup).not.toContain('Needs attention');+ expect(markup).not.toContain('Broken');+ expect(markup).toContain('Nothing waiting');+ expect(markup).not.toContain('0 B of 512 MB');+ expect(markup).not.toContain('Receiving pauses at');+ expect(markup).toContain('2 MB of 256 MB');+ expect(markup).toContain('At 256 MB Databasus starts a new chain from a full backup');+ expect(markup).toContain('Not saved to storage yet: 20 MB');+ expect(markup).toContain(+ 'Speeds are averages over the last 10 minutes; amounts are right now.',+ );+ expect(markup).toContain('Last change saved');});- it('keeps the technical names in details that start collapsed', () => {- const markup = renderWithLocale(<WalStreamDetailsComponent statistics={statistics} />);+ it('says nothing waits at both queues while the links still show the averaged rate of a database writing in bursts', () => {+ const statistics = createTestWalStreamStatistics();+ const burstyStatistics: WalStreamStatistics = {+ ...statistics,+ current: statistics.current && {+ ...statistics.current,+ slotLagBytes: 0,+ localQueueBytes: 0,+ },+ keepingUp: {+ ...statistics.keepingUp,+ slotLagBytes: 0,+ sourceWriteBytesPerSecond: 54.6 * 1024,+ archiveBytesPerSecond: 54.6 * 1024,+ },+ };++ const markup = renderWithLocale(+ <ChangesPathComponent+ statistics={burstyStatistics}+ stageTones={getStageTones(statistics.health.level, statistics.health.reasons)}+ isReducedMotion+ />,+ );++ expect(markup.match(/Nothing waiting/g)).toHaveLength(2);+ expect(markup).not.toContain('of 256 MB');+ expect(markup).not.toContain('of 512 MB');+ expect(markup.match(/54\.6 KB\/s/g)).toHaveLength(2);+ expect(markup).toContain(+ 'Speeds are averages over the last 10 minutes; amounts are right now.',+ );+ });- expect(markup).toContain('Details');- expect(markup).not.toContain('wal_status');+ it('shows an amount above its limit as over the limit, and puts each arrow behind its own breakpoint wrapper', () => {+ const statistics = createTestWalStreamStatistics();+ const pausedStatistics: WalStreamStatistics = {+ ...statistics,+ current: statistics.current && {+ ...statistics.current,+ localQueueBytes: 600 * MiB,+ isReceiverRunning: false,+ },+ };++ const markup = renderWithLocale(+ <ChangesPathComponent+ statistics={pausedStatistics}+ stageTones={getStageTones(brokenChainHealth.level, brokenChainHealth.reasons)}+ isReducedMotion+ />,+ );++ expect(markup).toContain('Over the limit');+ expect(markup).toContain('Receiving paused');+ expect(markup).toContain('Receiving pauses at 512 MB');+ expect(markup.match(/Needs attention/g)).toHaveLength(1);+ expect(markup).toMatch(+ /<span class="hidden @2xl:block" aria-hidden="true"><span[^>]*class="anticon anticon-arrow-right"/,+ );+ expect(markup).toMatch(+ /<span class="block text-gray-400 @2xl:hidden" aria-hidden="true"><span[^>]*class="anticon anticon-arrow-down"/,+ );});});diff --git a/frontend/src/features/backups/physical/monitoring/ui/WalStreamDetailsComponent.tsx b/frontend/src/features/backups/physical/monitoring/ui/WalStreamRawValuesComponent.tsxsimilarity index 78%rename from frontend/src/features/backups/physical/monitoring/ui/WalStreamDetailsComponent.tsxrename to frontend/src/features/backups/physical/monitoring/ui/WalStreamRawValuesComponent.tsxindex ea110847..3ae7554f 100644--- a/frontend/src/features/backups/physical/monitoring/ui/WalStreamDetailsComponent.tsx+++ b/frontend/src/features/backups/physical/monitoring/ui/WalStreamRawValuesComponent.tsx@@ -1,4 +1,3 @@-import { Collapse } from 'antd';import dayjs from 'dayjs';import { useTranslation } from 'react-i18next';@@ -16,10 +15,7 @@ interface Props {statistics: WalStreamStatistics;}-// eslint-disable-next-line i18next/no-literal-string -- Collapse item key-const DETAILS_PANEL_KEY = 'details';--export const WalStreamDetailsComponent = ({ statistics }: Props) => {+export const WalStreamRawValuesComponent = ({ statistics }: Props) => {const { t } = useTranslation();const { formatNumber } = useLocale();@@ -97,25 +93,13 @@ export const WalStreamDetailsComponent = ({ statistics }: Props) => {];return (- <Collapse- className="mt-6"- size="small"- items={[- {- key: DETAILS_PANEL_KEY,- label: t('backups.physical.monitoring.details.title'),- children: (- <dl className="grid grid-cols-1 gap-x-6 gap-y-2 text-sm md:grid-cols-2">- {rows.map((row) => (- <div key={row.labelKey} className="flex justify-between gap-4">- <dt className="text-gray-600 dark:text-gray-400">{t(row.labelKey)}</dt>- <dd className="text-right font-medium">{row.value}</dd>- </div>- ))}- </dl>- ),- },- ]}- />+ <dl className="grid grid-cols-1 gap-x-6 gap-y-2 text-sm md:grid-cols-2">+ {rows.map((row) => (+ <div key={row.labelKey} className="flex justify-between gap-4">+ <dt className="text-gray-600 dark:text-gray-400">{t(row.labelKey)}</dt>+ <dd className="text-right font-medium">{row.value}</dd>+ </div>+ ))}+ </dl>);};diff --git a/frontend/src/features/databases/ui/DatabaseComponent.tsx b/frontend/src/features/databases/ui/DatabaseComponent.tsxindex 1d7db6da..b9645cd9 100644--- a/frontend/src/features/databases/ui/DatabaseComponent.tsx+++ b/frontend/src/features/databases/ui/DatabaseComponent.tsx@@ -143,6 +143,7 @@ export const DatabaseComponent = ({{currentTab === 'monitoring' && isMonitoringShown && (<WalStreamMonitoringComponentdatabase={database}+ isCanManageDBs={isCanManageDBs}isDirectlyUnderTab={true}onOpenConfig={() => setCurrentTab('config')}/>diff --git a/frontend/src/features/databases/ui/DatabasesComponent.tsx b/frontend/src/features/databases/ui/DatabasesComponent.tsxindex 7e597bf1..c4d2d711 100644--- a/frontend/src/features/databases/ui/DatabasesComponent.tsx+++ b/frontend/src/features/databases/ui/DatabasesComponent.tsx@@ -20,6 +20,13 @@ interface Props {// eslint-disable-next-line i18next/no-literal-string -- localStorage keyconst SELECTED_DATABASE_STORAGE_KEY = 'selectedDatabaseId';+// A healthcheck can change a database's availability every minute, so the cards refresh twice as+// often to show the change within a minute.+const DATABASES_REFRESH_INTERVAL_MS = 30_000;++// eslint-disable-next-line i18next/no-literal-string -- DOM event name+const VISIBILITY_CHANGE_EVENT = 'visibilitychange';+export const DatabasesComponent = ({ contentHeight, workspace, isCanManageDBs }: Props) => {const { t } = useTranslation();const isMobile = useIsMobile();@@ -64,18 +71,31 @@ export const DatabasesComponent = ({ contentHeight, workspace, isCanManageDBs }:updateSelectedDatabaseId(databaseToSelect);}})- .catch((e) => alert(translateApiError(e, t)))+ .catch((e) => {+ // A background refresh retries on its own; an alert every 30 seconds would only get in the way.+ if (!isSilent) {+ alert(translateApiError(e, t));+ }+ }).finally(() => setIsLoading(false));};useEffect(() => {loadDatabases();- const interval = setInterval(() => {- loadDatabases(true);- }, 5 * 60_000);+ const refreshIfVisible = () => {+ if (document.visibilityState !== 'hidden') {+ loadDatabases(true);+ }+ };++ const interval = setInterval(refreshIfVisible, DATABASES_REFRESH_INTERVAL_MS);+ document.addEventListener(VISIBILITY_CHANGE_EVENT, refreshIfVisible);- return () => clearInterval(interval);+ return () => {+ clearInterval(interval);+ document.removeEventListener(VISIBILITY_CHANGE_EVENT, refreshIfVisible);+ };}, []);if (isLoading) {diff --git a/frontend/src/shared/i18n/locales/en.ts b/frontend/src/shared/i18n/locales/en.tsindex b465d053..674f4b02 100644--- a/frontend/src/shared/i18n/locales/en.ts+++ b/frontend/src/shared/i18n/locales/en.ts@@ -1695,6 +1695,22 @@ export const en = {cannotConfirm: 'Cannot confirm the current state',cannotConfirmDescription: 'Last known state: {{level}}, {{duration}} ago.',measuredAgo: 'Measured {{duration}} ago',+ healthyHeadline: 'All changes are being saved',+ restoreUpTo: 'You can restore the database to any moment up to {{moment}} ({{age}} ago).',+ restoreOnlyUpTo:+ 'Until a new full backup finishes, you can restore the database only up to {{moment}} ({{age}} ago).',+ restoreFromUpTo:+ 'You can restore the database to any moment from {{from}} up to {{moment}} ({{age}} ago).',+ restoreFromUpToWithoutAge:+ 'You can restore the database to any moment from {{from}} up to {{moment}}.',+ restoreUpToWithoutAge: 'You can restore the database to any moment up to {{moment}}.',+ restoreOnlyUpToWithoutAge:+ 'Until a new full backup finishes, you can restore the database only up to {{moment}}.',+ restoreNothingPending:+ 'Nothing can be restored until the first full backup finishes. It is on its way.',+ restoreNothing: 'Nothing can be restored yet, because no full backup has finished.',+ startFullBackup: 'Start full backup',+ fullBackupRequested: 'Full backup requested.',notMeasuredYet: 'Not measured yet',refreshFailed:'Could not refresh the data. The last received numbers stay on screen, and the next attempt runs in 30 seconds.',@@ -1710,7 +1726,6 @@ export const en = {'Databasus is saving a backlog: {{unsavedAmount}} is left, about {{duration}} to go.',catchingUpWithoutEstimate: 'Databasus is saving a backlog: {{unsavedAmount}} is left.',idle: 'The database writes almost nothing; new changes reach storage within minutes.',- unknown: 'No current numbers are available.',rebuildConsequence:'At this pace Databasus will start a new backup chain from a full backup in about {{duration}}.',limitConsequence:@@ -1730,7 +1745,7 @@ export const en = {walChainBroken: {title: 'Changes were lost between backups',whatHappened:- 'Some changes were lost between backups, so recent changes cannot be restored yet.',+ 'Part of the change history never reached storage, so the changes made after it cannot be restored.',whatToDo: 'Start a full backup on the Backups tab.',whatToDoPending:'A new full backup is on its way. You can watch it on the Backups tab.',@@ -1820,6 +1835,25 @@ export const en = {whatToDo: 'Wait for it, or start it on the Backups tab.',},},+ figures: {+ lastSaved: 'Last change saved',+ waitingToBeSaved: 'Waiting to be saved',+ notMeasured: 'Not measured yet',+ averageHint: 'avg. 10 min',+ },+ restoreTimeline: {+ title: 'What you can restore',+ restorable: 'Can be restored',+ lost: 'Cannot be restored',+ notSavedYet: 'Not saved to storage yet',+ lostSentence:+ 'You cannot restore the database to moments between {{from}} and {{to}}: these changes never reached storage.',+ moreLost: 'More stretches that cannot be restored: {{count}}.',+ range: '{{from}} – {{to}}',+ },+ technicalDetails: {+ title: 'Technical details',+ },path: {database: 'Database',databasus: 'Databasus',@@ -1827,18 +1861,21 @@ export const en = {notReceivedYet: 'Not received by Databasus yet',rebuildLimit: 'At {{amount}} Databasus starts a new chain from a full backup',allowanceLeft: 'Room before the database drops changes: {{amount}}',- noAllowanceLimit: 'No limit on kept changes',+ nothingWaiting: 'Nothing waiting',+ ratesCaption:+ 'Speeds are averages over the last 10 minutes; amounts are right now. A database that writes in bursts shows a speed while nothing waits.',waitingInBuffer: 'Waiting in the buffer',pauseLimit: 'Receiving pauses at {{amount}}',receivingPaused: 'Receiving paused',- lastSaved: 'Last change saved {{relativeTime}}',nothingSavedYet: 'Nothing saved yet',overLimit: 'Over the limit',- writeRate: 'Writes {{rate}}',- saveRate: 'Saves {{rate}}',+ ofLimit: '{{amount}} of {{limit}}',+ notSavedYetAmount: 'Not saved to storage yet: {{amount}}',unknownAmount: 'Unknown',},tooltips: {+ notSavedYet:+ 'Changes the database has written that are not in storage yet: those Databasus has not received plus those waiting in its buffer. Technical name: unarchived WAL.',notReceivedYet:'Changes the database keeps for Databasus because Databasus has not received them yet. Technical name: replication slot lag.',rebuildLimit:@@ -1869,12 +1906,13 @@ export const en = {pauseLimit: 'Receiving pauses here',restarts: 'Restarts',pauses: 'Pauses',- noHistory: 'Charts appear after a few minutes of streaming.',+ notEnoughData:+ 'Not enough data for this period yet. A shorter period may already have a chart.',dataSince: 'Data since {{time}}',+ noMeasurements: 'No measurements from {{from}} to {{to}}.',perSecond: '{{amount}}/s',},details: {- title: 'Details',slotStatus: 'Slot status (wal_status)',allowance: 'Remaining allowance (safe_wal_size)',noLimit: 'No limit',diff --git a/frontend/src/shared/i18n/locales/es.ts b/frontend/src/shared/i18n/locales/es.tsindex 79359566..752b7e4a 100644--- a/frontend/src/shared/i18n/locales/es.ts+++ b/frontend/src/shared/i18n/locales/es.ts@@ -1728,6 +1728,25 @@ export const es: typeof en = {cannotConfirm: 'No se puede confirmar el estado actual',cannotConfirmDescription: 'Último estado conocido: {{level}}, hace {{duration}}.',measuredAgo: 'Medido hace {{duration}}',+ healthyHeadline: 'Todos los cambios se están guardando',+ restoreUpTo:+ 'Puede restaurar la base de datos a cualquier momento hasta {{moment}} (hace {{age}}).',+ restoreOnlyUpTo:+ 'Hasta que termine una nueva copia completa, solo puede restaurar la base de datos hasta {{moment}} (hace {{age}}).',+ restoreFromUpTo:+ 'Puede restaurar la base de datos a cualquier momento desde {{from}} hasta {{moment}} (hace {{age}}).',+ restoreFromUpToWithoutAge:+ 'Puede restaurar la base de datos a cualquier momento desde {{from}} hasta {{moment}}.',+ restoreUpToWithoutAge:+ 'Puede restaurar la base de datos a cualquier momento hasta {{moment}}.',+ restoreOnlyUpToWithoutAge:+ 'Hasta que termine una nueva copia completa, solo puede restaurar la base de datos hasta {{moment}}.',+ restoreNothingPending:+ 'No se puede restaurar nada hasta que termine la primera copia completa. Ya está en camino.',+ restoreNothing:+ 'Todavía no se puede restaurar nada, porque ninguna copia completa ha terminado.',+ startFullBackup: 'Iniciar copia completa',+ fullBackupRequested: 'Copia completa solicitada.',notMeasuredYet: 'Aún no hay mediciones',refreshFailed:'No se pudieron actualizar los datos. Se siguen mostrando las últimas cifras recibidas y el próximo intento será en 30 segundos.',@@ -1744,7 +1763,6 @@ export const es: typeof en = {catchingUpWithoutEstimate:'Databasus está guardando los cambios acumulados: quedan {{unsavedAmount}}.',idle: 'La base de datos apenas escribe; los cambios nuevos llegan al almacenamiento en pocos minutos.',- unknown: 'No hay cifras actuales disponibles.',rebuildConsequence:'A este ritmo, Databasus empezará una nueva cadena de copias de seguridad con una copia completa en unos {{duration}}.',limitConsequence:@@ -1766,7 +1784,7 @@ export const es: typeof en = {walChainBroken: {title: 'Se perdieron cambios entre copias de seguridad',whatHappened:- 'Se perdieron algunos cambios entre copias de seguridad, por lo que los cambios recientes aún no se pueden restaurar.',+ 'Parte del historial de cambios nunca llegó al almacenamiento, por lo que los cambios posteriores no se pueden restaurar.',whatToDo: 'Inicie una copia de seguridad completa en la pestaña Copias de seguridad.',whatToDoPending:'Ya se está haciendo una nueva copia de seguridad completa. Puede seguirla en la pestaña Copias de seguridad.',@@ -1860,6 +1878,25 @@ export const es: typeof en = {whatToDo: 'Espere a que termine o iníciela en la pestaña Copias de seguridad.',},},+ figures: {+ lastSaved: 'Último cambio guardado',+ waitingToBeSaved: 'Pendiente de guardar',+ notMeasured: 'Aún sin medir',+ averageHint: 'prom. 10 min',+ },+ restoreTimeline: {+ title: 'Qué puede restaurar',+ restorable: 'Se puede restaurar',+ lost: 'No se puede restaurar',+ notSavedYet: 'Aún no guardado en el almacenamiento',+ lostSentence:+ 'No puede restaurar la base de datos a momentos entre {{from}} y {{to}}: esos cambios nunca llegaron al almacenamiento.',+ moreLost: 'Otros tramos que no se pueden restaurar: {{count}}.',+ range: '{{from}} – {{to}}',+ },+ technicalDetails: {+ title: 'Detalles técnicos',+ },path: {database: 'Base de datos',databasus: 'Databasus',@@ -1867,18 +1904,21 @@ export const es: typeof en = {notReceivedYet: 'Aún no recibido por Databasus',rebuildLimit: 'Con {{amount}}, Databasus empieza una nueva cadena con una copia completa',allowanceLeft: 'Margen antes de que la base de datos elimine cambios: {{amount}}',- noAllowanceLimit: 'Sin límite para los cambios conservados',+ nothingWaiting: 'Nada en espera',+ ratesCaption:+ 'Las velocidades son promedios de los últimos 10 minutos; las cantidades son las de este momento. Una base de datos que escribe a ráfagas muestra una velocidad aunque no haya nada en espera.',waitingInBuffer: 'En espera en el búfer',pauseLimit: 'La recepción se pausa con {{amount}}',receivingPaused: 'Recepción en pausa',- lastSaved: 'Último cambio guardado {{relativeTime}}',nothingSavedYet: 'Aún no se ha guardado nada',overLimit: 'Por encima del límite',- writeRate: 'Escribe {{rate}}',- saveRate: 'Guarda {{rate}}',+ ofLimit: '{{amount}} de {{limit}}',+ notSavedYetAmount: 'Aún no guardado en el almacenamiento: {{amount}}',unknownAmount: 'Desconocido',},tooltips: {+ notSavedYet:+ 'Cambios que la base de datos ha escrito y que aún no están en el almacenamiento: los que Databasus no ha recibido más los que esperan en su búfer. Nombre técnico: WAL sin archivar.',notReceivedYet:'Cambios que la base de datos conserva para Databasus porque Databasus aún no los ha recibido. Nombre técnico: retraso del slot de replicación.',rebuildLimit:@@ -1909,12 +1949,13 @@ export const es: typeof en = {pauseLimit: 'Aquí se pausa la recepción',restarts: 'Reinicios',pauses: 'Pausas',- noHistory: 'Los gráficos aparecerán tras unos minutos de streaming.',+ notEnoughData:+ 'Todavía no hay datos suficientes para este período. Puede que un período más corto ya tenga gráfico.',dataSince: 'Datos desde {{time}}',+ noMeasurements: 'Sin mediciones desde {{from}} hasta {{to}}.',perSecond: '{{amount}}/s',},details: {- title: 'Detalles',slotStatus: 'Estado del slot (wal_status)',allowance: 'Margen restante (safe_wal_size)',noLimit: 'Sin límite',diff --git a/frontend/src/shared/i18n/locales/fr.ts b/frontend/src/shared/i18n/locales/fr.tsindex a6b65dfc..5a7e40d9 100644--- a/frontend/src/shared/i18n/locales/fr.ts+++ b/frontend/src/shared/i18n/locales/fr.ts@@ -1738,6 +1738,25 @@ export const fr: typeof en = {cannotConfirm: "Impossible de confirmer l'état actuel",cannotConfirmDescription: 'Dernier état connu : {{level}}, il y a {{duration}}.',measuredAgo: 'Mesuré il y a {{duration}}',+ healthyHeadline: 'Toutes les modifications sont enregistrées',+ restoreUpTo:+ "Vous pouvez restaurer la base à n'importe quel moment jusqu'à {{moment}} (il y a {{age}}).",+ restoreOnlyUpTo:+ "Tant qu'une nouvelle sauvegarde complète n'est pas terminée, vous ne pouvez restaurer la base que jusqu'à {{moment}} (il y a {{age}}).",+ restoreFromUpTo:+ "Vous pouvez restaurer la base à n'importe quel moment entre {{from}} et {{moment}} (il y a {{age}}).",+ restoreFromUpToWithoutAge:+ "Vous pouvez restaurer la base à n'importe quel moment entre {{from}} et {{moment}}.",+ restoreUpToWithoutAge:+ "Vous pouvez restaurer la base à n'importe quel moment jusqu'à {{moment}}.",+ restoreOnlyUpToWithoutAge:+ "Tant qu'une nouvelle sauvegarde complète n'est pas terminée, vous ne pouvez restaurer la base que jusqu'à {{moment}}.",+ restoreNothingPending:+ "Rien ne peut être restauré tant que la première sauvegarde complète n'est pas terminée. Elle est déjà en route.",+ restoreNothing:+ "Rien ne peut encore être restauré, car aucune sauvegarde complète n'est terminée.",+ startFullBackup: 'Lancer une sauvegarde complète',+ fullBackupRequested: 'Sauvegarde complète demandée.',notMeasuredYet: 'Pas encore de mesure',refreshFailed:"Impossible d'actualiser les données. Les derniers chiffres reçus restent affichés, et la prochaine tentative a lieu dans 30 secondes.",@@ -1754,7 +1773,6 @@ export const fr: typeof en = {catchingUpWithoutEstimate:'Databasus enregistre le retard accumulé : il reste {{unsavedAmount}}.',idle: "La base de données n'écrit presque rien ; les nouvelles modifications arrivent dans le stockage en quelques minutes.",- unknown: "Aucun chiffre actuel n'est disponible.",rebuildConsequence:"À ce rythme, Databasus commencera une nouvelle chaîne de sauvegardes à partir d'une sauvegarde complète dans environ {{duration}}.",limitConsequence:@@ -1777,7 +1795,7 @@ export const fr: typeof en = {walChainBroken: {title: 'Des modifications ont été perdues entre les sauvegardes',whatHappened:- 'Des modifications ont été perdues entre les sauvegardes, les modifications récentes ne peuvent donc pas encore être restaurées.',+ "Une partie de l'historique des modifications n'a jamais atteint le stockage, les modifications suivantes ne peuvent donc pas être restaurées.",whatToDo: "Lancez une sauvegarde complète dans l'onglet Sauvegardes.",whatToDoPending:"Une nouvelle sauvegarde complète est en cours. Vous pouvez la suivre dans l'onglet Sauvegardes.",@@ -1874,6 +1892,25 @@ export const fr: typeof en = {whatToDo: "Attendez-la, ou lancez-la dans l'onglet Sauvegardes.",},},+ figures: {+ lastSaved: 'Dernière modification enregistrée',+ waitingToBeSaved: "En attente d'enregistrement",+ notMeasured: 'Pas encore mesuré',+ averageHint: 'moy. 10 min',+ },+ restoreTimeline: {+ title: 'Ce que vous pouvez restaurer',+ restorable: 'Restaurable',+ lost: 'Non restaurable',+ notSavedYet: 'Pas encore enregistré dans le stockage',+ lostSentence:+ "Vous ne pouvez pas restaurer la base à un moment entre {{from}} et {{to}} : ces modifications n'ont jamais atteint le stockage.",+ moreLost: 'Autres périodes non restaurables : {{count}}.',+ range: '{{from}} – {{to}}',+ },+ technicalDetails: {+ title: 'Détails techniques',+ },path: {database: 'Base de données',databasus: 'Databasus',@@ -1883,18 +1920,21 @@ export const fr: typeof en = {"À {{amount}}, Databasus commence une nouvelle chaîne à partir d'une sauvegarde complète",allowanceLeft:'Marge avant que la base de données ne supprime des modifications : {{amount}}',- noAllowanceLimit: 'Aucune limite sur les modifications conservées',+ nothingWaiting: 'Rien en attente',+ ratesCaption:+ "Les débits sont des moyennes sur les 10 dernières minutes ; les volumes sont ceux de cet instant. Une base qui écrit par à-coups affiche un débit alors que rien n'attend.",waitingInBuffer: 'En attente dans le tampon',pauseLimit: 'La réception est suspendue à {{amount}}',receivingPaused: 'Réception suspendue',- lastSaved: 'Dernière modification enregistrée {{relativeTime}}',nothingSavedYet: "Rien n'est encore enregistré",overLimit: 'Au-delà de la limite',- writeRate: 'Écrit {{rate}}',- saveRate: 'Enregistre {{rate}}',+ ofLimit: '{{amount}} sur {{limit}}',+ notSavedYetAmount: 'Pas encore enregistré dans le stockage : {{amount}}',unknownAmount: 'Inconnu',},tooltips: {+ notSavedYet:+ "Modifications écrites par la base qui ne sont pas encore dans le stockage : celles que Databasus n'a pas reçues et celles qui attendent dans sa mémoire tampon. Nom technique : WAL non archivé.",notReceivedYet:'Modifications que la base de données conserve pour Databasus parce que Databasus ne les a pas encore reçues. Nom technique : retard du slot de réplication.',rebuildLimit:@@ -1925,12 +1965,13 @@ export const fr: typeof en = {pauseLimit: 'La réception est suspendue ici',restarts: 'Redémarrages',pauses: 'Pauses',- noHistory: 'Les graphiques apparaissent après quelques minutes de streaming.',+ notEnoughData:+ 'Pas encore assez de données pour cette période. Une période plus courte a peut-être déjà un graphique.',dataSince: 'Données depuis {{time}}',+ noMeasurements: 'Aucune mesure de {{from}} à {{to}}.',perSecond: '{{amount}}/s',},details: {- title: 'Détails',slotStatus: 'Statut du slot (wal_status)',allowance: 'Marge restante (safe_wal_size)',noLimit: 'Aucune limite',diff --git a/frontend/src/shared/i18n/locales/pt.ts b/frontend/src/shared/i18n/locales/pt.tsindex a2114688..008c2f3d 100644--- a/frontend/src/shared/i18n/locales/pt.ts+++ b/frontend/src/shared/i18n/locales/pt.ts@@ -1721,6 +1721,25 @@ export const pt: typeof en = {cannotConfirm: 'Não é possível confirmar o estado atual',cannotConfirmDescription: 'Último estado conhecido: {{level}}, há {{duration}}.',measuredAgo: 'Medido há {{duration}}',+ healthyHeadline: 'Todas as alterações estão sendo salvas',+ restoreUpTo:+ 'Você pode restaurar o banco de dados para qualquer momento até {{moment}} (há {{age}}).',+ restoreOnlyUpTo:+ 'Até que um novo backup completo termine, você só pode restaurar o banco de dados até {{moment}} (há {{age}}).',+ restoreFromUpTo:+ 'Você pode restaurar o banco de dados para qualquer momento de {{from}} até {{moment}} (há {{age}}).',+ restoreFromUpToWithoutAge:+ 'Você pode restaurar o banco de dados para qualquer momento de {{from}} até {{moment}}.',+ restoreUpToWithoutAge:+ 'Você pode restaurar o banco de dados para qualquer momento até {{moment}}.',+ restoreOnlyUpToWithoutAge:+ 'Até que um novo backup completo termine, você só pode restaurar o banco de dados até {{moment}}.',+ restoreNothingPending:+ 'Nada pode ser restaurado até que o primeiro backup completo termine. Ele já está a caminho.',+ restoreNothing:+ 'Ainda não há nada para restaurar, porque nenhum backup completo terminou.',+ startFullBackup: 'Iniciar backup completo',+ fullBackupRequested: 'Backup completo solicitado.',notMeasuredYet: 'Ainda sem medições',refreshFailed:'Não foi possível atualizar os dados. Os últimos números recebidos continuam na tela, e a próxima tentativa acontece em 30 segundos.',@@ -1737,7 +1756,6 @@ export const pt: typeof en = {catchingUpWithoutEstimate:'O Databasus está salvando as alterações acumuladas: faltam {{unsavedAmount}}.',idle: 'O banco de dados quase não grava nada; as novas alterações chegam ao armazenamento em poucos minutos.',- unknown: 'Não há números atuais disponíveis.',rebuildConsequence:'Nesse ritmo, o Databasus vai começar uma nova cadeia de backups a partir de um backup completo em cerca de {{duration}}.',limitConsequence:@@ -1759,7 +1777,7 @@ export const pt: typeof en = {walChainBroken: {title: 'Alterações se perderam entre os backups',whatHappened:- 'Algumas alterações se perderam entre os backups, por isso as alterações recentes ainda não podem ser restauradas.',+ 'Parte do histórico de alterações nunca chegou ao armazenamento, por isso as alterações posteriores não podem ser restauradas.',whatToDo: 'Inicie um backup completo na aba Backups.',whatToDoPending:'Um novo backup completo já está a caminho. Você pode acompanhá-lo na aba Backups.',@@ -1852,6 +1870,25 @@ export const pt: typeof en = {whatToDo: 'Aguarde ou inicie-o na aba Backups.',},},+ figures: {+ lastSaved: 'Última alteração salva',+ waitingToBeSaved: 'Aguardando para ser salvo',+ notMeasured: 'Ainda não medido',+ averageHint: 'méd. 10 min',+ },+ restoreTimeline: {+ title: 'O que você pode restaurar',+ restorable: 'Pode ser restaurado',+ lost: 'Não pode ser restaurado',+ notSavedYet: 'Ainda não salvo no armazenamento',+ lostSentence:+ 'Você não pode restaurar o banco de dados para momentos entre {{from}} e {{to}}: essas alterações nunca chegaram ao armazenamento.',+ moreLost: 'Outros períodos que não podem ser restaurados: {{count}}.',+ range: '{{from}} – {{to}}',+ },+ technicalDetails: {+ title: 'Detalhes técnicos',+ },path: {database: 'Banco de dados',databasus: 'Databasus',@@ -1860,18 +1897,21 @@ export const pt: typeof en = {rebuildLimit:'Com {{amount}}, o Databasus começa uma nova cadeia a partir de um backup completo',allowanceLeft: 'Margem até o banco de dados apagar alterações: {{amount}}',- noAllowanceLimit: 'Sem limite para alterações guardadas',+ nothingWaiting: 'Nada aguardando',+ ratesCaption:+ 'As velocidades são médias dos últimos 10 minutos; as quantidades são as deste momento. Um banco de dados que grava em rajadas mostra uma velocidade mesmo sem nada aguardando.',waitingInBuffer: 'Aguardando no buffer',pauseLimit: 'O recebimento pausa com {{amount}}',receivingPaused: 'Recebimento pausado',- lastSaved: 'Última alteração salva {{relativeTime}}',nothingSavedYet: 'Nada salvo ainda',overLimit: 'Acima do limite',- writeRate: 'Grava {{rate}}',- saveRate: 'Salva {{rate}}',+ ofLimit: '{{amount}} de {{limit}}',+ notSavedYetAmount: 'Ainda não salvo no armazenamento: {{amount}}',unknownAmount: 'Desconhecido',},tooltips: {+ notSavedYet:+ 'Alterações que o banco de dados gravou e que ainda não estão no armazenamento: as que o Databasus não recebeu mais as que aguardam no buffer dele. Nome técnico: WAL não arquivado.',notReceivedYet:'Alterações que o banco de dados guarda para o Databasus porque o Databasus ainda não as recebeu. Nome técnico: atraso do slot de replicação.',rebuildLimit:@@ -1902,12 +1942,13 @@ export const pt: typeof en = {pauseLimit: 'Aqui o recebimento pausa',restarts: 'Reinícios',pauses: 'Pausas',- noHistory: 'Os gráficos aparecem após alguns minutos de streaming.',+ notEnoughData:+ 'Ainda não há dados suficientes para este período. Um período mais curto talvez já tenha um gráfico.',dataSince: 'Dados desde {{time}}',+ noMeasurements: 'Sem medições de {{from}} até {{to}}.',perSecond: '{{amount}}/s',},details: {- title: 'Detalhes',slotStatus: 'Status do slot (wal_status)',allowance: 'Margem restante (safe_wal_size)',noLimit: 'Sem limite',diff --git a/frontend/src/shared/i18n/locales/ru.ts b/frontend/src/shared/i18n/locales/ru.tsindex 94a2a9d4..00a89d69 100644--- a/frontend/src/shared/i18n/locales/ru.ts+++ b/frontend/src/shared/i18n/locales/ru.ts@@ -1701,6 +1701,22 @@ export const ru: typeof en = {cannotConfirm: 'Не удается подтвердить текущее состояние',cannotConfirmDescription: 'Последнее известное состояние: {{level}}, {{duration}} назад.',measuredAgo: 'Замер {{duration}} назад',+ healthyHeadline: 'Все изменения сохраняются',+ restoreUpTo: 'Базу можно восстановить на любой момент до {{moment}} ({{age}} назад).',+ restoreOnlyUpTo:+ 'Пока не завершится новый полный бекап, базу можно восстановить только до {{moment}} ({{age}} назад).',+ restoreFromUpTo:+ 'Базу можно восстановить на любой момент с {{from}} до {{moment}} ({{age}} назад).',+ restoreFromUpToWithoutAge:+ 'Базу можно восстановить на любой момент с {{from}} до {{moment}}.',+ restoreUpToWithoutAge: 'Базу можно восстановить на любой момент до {{moment}}.',+ restoreOnlyUpToWithoutAge:+ 'Пока не завершится новый полный бекап, базу можно восстановить только до {{moment}}.',+ restoreNothingPending:+ 'Восстановить ничего не получится, пока не завершится первый полный бекап. Он уже запрошен.',+ restoreNothing: 'Восстанавливать пока нечего: ни один полный бекап еще не завершился.',+ startFullBackup: 'Запустить полный бекап',+ fullBackupRequested: 'Полный бекап запрошен.',notMeasuredYet: 'Замеров еще нет',refreshFailed:'Не удалось обновить данные. На экране остаются последние полученные цифры, следующая попытка через 30 секунд.',@@ -1717,7 +1733,6 @@ export const ru: typeof en = {catchingUpWithoutEstimate:'Databasus сохраняет накопившиеся изменения: осталось {{unsavedAmount}}.',idle: 'База почти ничего не пишет, новые изменения попадают в хранилище в течение нескольких минут.',- unknown: 'Текущих цифр пока нет.',rebuildConsequence:'Если так пойдет дальше, примерно через {{duration}} Databasus начнет новую цепочку бекапов с полного бекапа.',limitConsequence:@@ -1738,7 +1753,7 @@ export const ru: typeof en = {walChainBroken: {title: 'Между бекапами потерялись изменения',whatHappened:- 'Часть изменений между бекапами потерялась, поэтому последние изменения пока нельзя восстановить.',+ 'Часть истории изменений не дошла до хранилища, поэтому изменения после неё восстановить нельзя.',whatToDo: 'Запустите полный бекап на вкладке «Бекапы».',whatToDoPending:'Новый полный бекап уже в работе, за ним можно следить на вкладке «Бекапы».',@@ -1828,6 +1843,25 @@ export const ru: typeof en = {whatToDo: 'Дождитесь его или запустите на вкладке «Бекапы».',},},+ figures: {+ lastSaved: 'Последнее изменение сохранено',+ waitingToBeSaved: 'Ждет сохранения',+ notMeasured: 'Еще не измерено',+ averageHint: 'в среднем за 10 мин',+ },+ restoreTimeline: {+ title: 'Что можно восстановить',+ restorable: 'Можно восстановить',+ lost: 'Нельзя восстановить',+ notSavedYet: 'Ещё не сохранено в хранилище',+ lostSentence:+ 'Базу нельзя восстановить на моменты между {{from}} и {{to}}: эти изменения не дошли до хранилища.',+ moreLost: 'Других промежутков, на которые нельзя восстановить: {{count}}.',+ range: '{{from}} – {{to}}',+ },+ technicalDetails: {+ title: 'Технические подробности',+ },path: {database: 'База',databasus: 'Databasus',@@ -1835,18 +1869,21 @@ export const ru: typeof en = {notReceivedYet: 'Еще не получено Databasus',rebuildLimit: 'При {{amount}} Databasus начнет новую цепочку с полного бекапа',allowanceLeft: 'Запас, пока база не начнет удалять изменения: {{amount}}',- noAllowanceLimit: 'Предела для хранимых изменений нет',+ nothingWaiting: 'Ничего не ждёт',+ ratesCaption:+ 'Скорости — средние за последние 10 минут, объёмы — на текущий момент. Если база пишет пачками, скорость есть, а ждать нечему.',waitingInBuffer: 'Ждет в буфере',pauseLimit: 'Прием приостанавливается при {{amount}}',receivingPaused: 'Прием приостановлен',- lastSaved: 'Последнее изменение сохранено {{relativeTime}}',nothingSavedYet: 'Пока ничего не сохранено',overLimit: 'Сверх предела',- writeRate: 'Запись {{rate}}',- saveRate: 'Сохранение {{rate}}',+ ofLimit: '{{amount}} из {{limit}}',+ notSavedYetAmount: 'Ещё не сохранено в хранилище: {{amount}}',unknownAmount: 'Неизвестно',},tooltips: {+ notSavedYet:+ 'Изменения, которые база уже записала, но которых ещё нет в хранилище: то, что Databasus ещё не получил, и то, что ждёт в его буфере. Технически это неархивированный WAL.',notReceivedYet:'Изменения, которые база держит для Databasus, потому что Databasus их еще не получил. Технически это отставание слота репликации.',rebuildLimit:@@ -1877,12 +1914,13 @@ export const ru: typeof en = {pauseLimit: 'Здесь прием приостанавливается',restarts: 'Перезапуски',pauses: 'Паузы',- noHistory: 'Графики появятся через несколько минут стриминга.',+ notEnoughData:+ 'Для этого периода данных пока мало. Для периода покороче график, возможно, уже есть.',dataSince: 'Данные с {{time}}',+ noMeasurements: 'Нет измерений с {{from}} до {{to}}.',perSecond: '{{amount}}/с',},details: {- title: 'Подробности',slotStatus: 'Статус слота (wal_status)',allowance: 'Оставшийся запас (safe_wal_size)',noLimit: 'Без предела',diff --git a/frontend/src/shared/i18n/locales/zh.ts b/frontend/src/shared/i18n/locales/zh.tsindex c0bfcd19..1402299e 100644--- a/frontend/src/shared/i18n/locales/zh.ts+++ b/frontend/src/shared/i18n/locales/zh.ts@@ -1631,6 +1631,17 @@ export const zh: typeof en = {cannotConfirm: '无法确认当前状态',cannotConfirmDescription: '最后已知状态:{{level}},{{duration}}前。',measuredAgo: '{{duration}}前测量',+ healthyHeadline: '所有变更都在保存',+ restoreUpTo: '可以把数据库恢复到 {{moment}}({{age}}前)之前的任意时刻。',+ restoreOnlyUpTo: '在新的完整备份完成之前,数据库只能恢复到 {{moment}}({{age}}前)。',+ restoreFromUpTo: '可以把数据库恢复到 {{from}} 至 {{moment}}({{age}}前)之间的任意时刻。',+ restoreFromUpToWithoutAge: '可以把数据库恢复到 {{from}} 至 {{moment}} 之间的任意时刻。',+ restoreUpToWithoutAge: '数据库可以恢复到 {{moment}} 之前的任意时刻。',+ restoreOnlyUpToWithoutAge: '在新的完整备份完成之前,数据库只能恢复到 {{moment}}。',+ restoreNothingPending: '第一次完整备份完成之前无法恢复任何内容。该备份已在进行中。',+ restoreNothing: '暂时没有可恢复的内容,因为还没有任何完整备份完成。',+ startFullBackup: '启动完整备份',+ fullBackupRequested: '已请求完整备份。',notMeasuredYet: '尚无测量',refreshFailed: '数据刷新失败。屏幕上保留最后收到的数据,30 秒后会再次尝试。',},@@ -1645,7 +1656,6 @@ export const zh: typeof en = {'Databasus 正在保存积压的变更:还剩 {{unsavedAmount}},大约需要 {{duration}}。',catchingUpWithoutEstimate: 'Databasus 正在保存积压的变更:还剩 {{unsavedAmount}}。',idle: '数据库几乎没有写入,新的变更会在几分钟内进入存储。',- unknown: '暂无当前数据。',rebuildConsequence:'按这个速度,大约 {{duration}}后 Databasus 将从完整备份开始新的备份链。',limitConsequence:@@ -1664,7 +1674,7 @@ export const zh: typeof en = {},walChainBroken: {title: '备份之间丢失了变更',- whatHappened: '备份之间丢失了部分变更,因此最近的变更暂时无法恢复。',+ whatHappened: '部分变更历史未能到达存储,因此之后的变更无法恢复。',whatToDo: '请在“备份”标签页启动一次完整备份。',whatToDoPending: '新的完整备份已在进行中,可以在“备份”标签页查看进度。',},@@ -1743,6 +1753,24 @@ export const zh: typeof en = {whatToDo: '请等待它完成,或在“备份”标签页启动。',},},+ figures: {+ lastSaved: '最近一次变更保存于',+ waitingToBeSaved: '等待保存',+ notMeasured: '尚未测量',+ averageHint: '10 分钟平均',+ },+ restoreTimeline: {+ title: '可以恢复到哪些时刻',+ restorable: '可以恢复',+ lost: '无法恢复',+ notSavedYet: '尚未保存到存储',+ lostSentence: '数据库无法恢复到 {{from}} 至 {{to}} 之间的时刻:这些变更从未到达存储。',+ moreLost: '其他无法恢复的时间段:{{count}}。',+ range: '{{from}} 至 {{to}}',+ },+ technicalDetails: {+ title: '技术详情',+ },path: {database: '数据库',databasus: 'Databasus',@@ -1750,18 +1778,21 @@ export const zh: typeof en = {notReceivedYet: 'Databasus 尚未接收',rebuildLimit: '达到 {{amount}} 时 Databasus 将从完整备份开始新的链',allowanceLeft: '数据库开始删除变更前的余量:{{amount}}',- noAllowanceLimit: '保留的变更没有上限',+ nothingWaiting: '没有等待中的变更',+ ratesCaption:+ '速度是最近 10 分钟的平均值,数量是当前值。数据库分批写入时,会显示速度,但没有等待中的变更。',waitingInBuffer: '缓冲区中等待',pauseLimit: '达到 {{amount}} 时暂停接收',receivingPaused: '接收已暂停',- lastSaved: '最后一次保存变更:{{relativeTime}}',nothingSavedYet: '尚未保存任何内容',overLimit: '超出上限',- writeRate: '写入 {{rate}}',- saveRate: '保存 {{rate}}',+ ofLimit: '{{amount}} / {{limit}}',+ notSavedYetAmount: '尚未保存到存储:{{amount}}',unknownAmount: '未知',},tooltips: {+ notSavedYet:+ '数据库已写入但尚未进入存储的变更:包括 Databasus 尚未接收的部分和在其缓冲区中等待的部分。技术名称:未归档的 WAL。',notReceivedYet:'数据库为 Databasus 保留的、Databasus 尚未接收的变更。技术名称:复制槽延迟。',rebuildLimit:@@ -1789,12 +1820,12 @@ export const zh: typeof en = {pauseLimit: '在此暂停接收',restarts: '重启',pauses: '暂停',- noHistory: '流式传输几分钟后会显示图表。',+ notEnoughData: '该时间段的数据还不够。更短的时间段可能已经有图表。',dataSince: '数据起始于 {{time}}',+ noMeasurements: '{{from}} 至 {{to}} 之间没有测量数据。',perSecond: '{{amount}}/秒',},details: {- title: '详细信息',slotStatus: '槽状态(wal_status)',allowance: '剩余余量(safe_wal_size)',noLimit: '无上限',diff --git a/openspec/changes/archive/2026-10-21-rethink-wal-monitoring-tab/.openspec.yaml b/openspec/changes/archive/2026-10-21-rethink-wal-monitoring-tab/.openspec.yamlnew file mode 100644index 00000000..9076a660--- /dev/null+++ b/openspec/changes/archive/2026-10-21-rethink-wal-monitoring-tab/.openspec.yaml@@ -0,0 +1,2 @@+schema: spec-driven+created: 2026-10-20diff --git a/openspec/changes/archive/2026-10-21-rethink-wal-monitoring-tab/design.md b/openspec/changes/archive/2026-10-21-rethink-wal-monitoring-tab/design.mdnew file mode 100644index 00000000..d3f965f2--- /dev/null+++ b/openspec/changes/archive/2026-10-21-rethink-wal-monitoring-tab/design.md@@ -0,0 +1,240 @@+## Context++See proposal.md for the motivation and specs/physical-backups/wal-stream-monitoring/spec.md for the requirements. Frontend paths below are under `frontend/src/`, and `<mon>` stands for `features/backups/physical/monitoring`. Backend paths are under `backend/internal/features/backups/backups/`.++What exists today:++- The tab renders five blocks in a fixed order (`<mon>/ui/WalStreamMonitoringComponent.tsx:188-225`): the verdict banner, the reasons list, the path of changes, the charts and the details.+- The banner's headline is the level label (`<mon>/lib/verdictBanner.ts:57-61`), so a broken verdict reads "Something is broken" (`shared/i18n/locales/en.ts`, `monitoring.levels`). For every verdict about streaming, the banner also shows the keeping-up sentence (`WalStreamMonitoringComponent.tsx:190-194`). That is why "The database writes almost nothing" appears under a broken chain.+- The reasons and the notices render in a separate component below the banner (`<mon>/ui/MonitoringReasonsComponent.tsx`). The notices share one blue `Alert`, and the no slot WAL limit notice sits there as a `Collapse` (`MonitoringReasonsComponent.tsx:56-80`).+- `REASON_STAGES` maps `WAL_CHAIN_BROKEN` to the storage stage (`<mon>/lib/reasonTexts.ts:20`), and `getStageTones` colors that stage red (`<mon>/lib/pathStages.ts:33-43`). The storage card then turns red while it says that the last change was saved seconds ago.+- Each arrow between stages renders `ArrowRightOutlined` with `hidden md:block` and `ArrowDownOutlined` with `md:hidden` (`<mon>/ui/ChangesPathComponent.tsx:130-131`). At 1440 px both are visible. The likely cause is that AntD's `.anticon { display: inline-flex }` rule wins over Tailwind's `hidden` on the icon element itself.+- The charts' time axis always spans the whole period (`<mon>/ui/WalStreamChartsComponent.tsx:115`), and the amount axis scales to the data (`:120`). The empty state appears only when no point has values (`<mon>/lib/chartRows.ts:25-26`).+- The statistics response holds `health`, `streamer`, `current`, `keepingUp` and `series` (`dto/physical/wal_stream_statistics.go:42-48`). Nothing in it says to which moment the backups can restore.+- A restore to the latest available point is resolved by `ChainViewService.ResolveRestoreSet(databaseID, nil)` (`core/physical/chain_view/restore_set.go:41-102`). It takes the newest chain and its completed incrementals; `includedIncrementals` moves the starting point to the newest completed incremental's stop LSN (`restore_set.go:243-273`). `contiguousWalRun` then skips WAL below that point, stops at the first gap above it and returns the reachable time: the `ReceivedAt` of the last contiguous segment, or the last backup's completion time without WAL (`restore_set.go:275-302`). A gap below the newest incremental therefore does not limit the latest restore, and a lossy chain stays extendable, so incrementals keep completing after a gap (`chain_view/service.go:248-251`). The existing test `Test_ResolveRestoreSet_WhenLatestWithGap_ResolvesToPreGapCeilingWithoutError` pins the gap case without a later incremental (`restore_set_test.go:275`).+- The statistics service already reads the newest full backup's gaps on every request (`services/physical_wal_stream_statistics.go:55`). `FindWalGapsInChain` lists every gap between consecutive segments of the chain (`chain_view/service.go:106-146`), and `getWalChainBrokenReason` reports the chain broken for any of them below the archive progress point (`core/physical/wal_health/verdict.go:222-235`). Neither looks at incrementals, so a gap that a completed incremental bridges keeps the verdict broken while the restore already crosses it. A live database showed exactly that: a red "Changes were lost between backups" next to a correct "You can restore … up to 3:17 PM (12 min ago)".+- A full backup is requested through `POST /backups/physical/database/:id/trigger` with type `full` (`controllers/physical/controller.go:155-186`). `RequestFullBackup` authorizes through `authorizeManage` and sets `ForceFullRequestedAt` before it answers (`services/physical_service.go:165-183`, `backend/internal/features/backups/config/physical/service.go:225`), and the statistics read exactly that field as a pending full backup (`services/physical_wal_stream_statistics.go:93-96`). `WalStreamRefreshController.retry()` refreshes at once (`<mon>/lib/walStreamRefreshController.ts:74`). The frontend calls it through `physicalBackupsApi.triggerPhysicalBackup(databaseId, 'full')` (`entity/backups/physical/api/physicalBackupsApi.ts:34`), and the Backups tab does so from a dropdown without a confirmation dialog (`features/backups/physical/ui/PhysicalBackupsComponent.tsx:167-179`, `:398-408`).+- `DatabaseComponent` knows `isCanManageDBs` and passes it to the Backups tab, but not to the Monitoring tab (`features/databases/ui/DatabaseComponent.tsx:143-148`).+- Frontend tests run in vitest with the `node` environment (`frontend/vitest.config.ts:12`). UI tests render static markup (`<mon>/ui/WalStreamMonitoringSections.test.tsx`), so click handling cannot be exercised there.++Constraints:++- `frontend/AGENTS.md`: AntD, `@ant-design/icons` and Tailwind only; no literal user-facing strings; every key in all six dictionaries; counts phrased so one string fits every number; code outside components holds keys, not text; `useLocale()` for `formatNumber` and `formatRelativeTime`; API errors through `translateApiError`; FSD imports only downward; one type per file in `model/`.+- `backend/AGENTS.md`: controller tests preferred; Swagger annotations on every endpoint, regenerated docs; no injecting another feature's repository; `time.Now().UTC()`.+- `AGENTS.md`: no backward-compatibility shims; refactor the code the change touches.++## Goals / Non-Goals++**Goals:**++- The tab and the restore name the same restorable moment, by construction.+- The rules that decide what the banner, the figures and the charts show stay pure functions in `<mon>/lib`, so vitest covers them without a DOM.+- Removed blocks leave no unused component, helper or dictionary key behind.++**Non-Goals:**++- A DOM test environment for the frontend. The click flow of the full backup button is covered through its pure state function.+- Changing the verdict rules in `core/physical/wal_health`. Only the meaning of the gaps it receives changes (D1), and the input field is renamed to say so.++## Decisions++### D1. The restorable moment comes from the restore's own resolution++`ResolveRestoreSet` is split. A new private method resolves the latest reach of a database: it selects the newest chain, its completed incrementals and the contiguous WAL run after the newest of them, and returns them with the reachable LSN and time. A gap below the newest completed backup does not limit the reach, exactly as in a restore today. `ResolveRestoreSet` calls it and adds the history files and the target checks it has today; `GetRestoreCoverage` below calls it too. Both paths share `orderedRestoreCandidates`, `selectRestoreChain`, `includedIncrementals` and `contiguousWalRun`, so a later change to restore resolution changes the tab with it.++The public read is `ChainViewService.GetRestoreCoverage(databaseID) (*RestoreCoverage, error)`, which replaces the first version's `GetLatestRestorableAt`:++```go+type TimeRange struct{ From, To time.Time }++type RestoreCoverage struct {+ LatestRestorableAt *time.Time // nil without a restorable chain+ RestorableRanges []TimeRange // newest chain, oldest first, merged+ BlockingGaps []LSNRange // gaps the latest restore cannot cross+}+```++- `LatestRestorableAt` is the latest reach's time. `ErrNoChainForRestore` gives an empty coverage, not an error.+- `BlockingGaps` are `FindWalGapsInChain(chain.RootFull.ID)` filtered to `gap.End > reach.lastStopLSN`, the stop LSN of the newest completed backup of the chain. That is exactly where `contiguousWalRun` stops; a gap with `End <= lastStopLSN` is bridged. `FindWalGapsInChain` itself stays as it is, because the Backups tab and `WaitForWalGap` read every gap.+- `RestorableRanges`: every anchor, the full backup and each completed incremental chosen by the same filter as `includedIncrementals`, opens `[anchor.CompletedAt, time the contiguous WAL run from anchor.StopLSN reaches]`, and overlapping or touching ranges merge. Calling `contiguousWalRun` once per anchor costs anchors × segments, so one backward pass over the sorted segments stores the end of each segment's contiguous run, and a binary search finds the segment that holds each anchor's stop LSN. The last range ends at `LatestRestorableAt` by construction.++The statistics service calls `GetRestoreCoverage` once and passes `BlockingGaps` to the verdict, which renames `NewestChainGaps` to `RestoreBlockingGaps` in `wal_health/dto.go` and `core/physical/service/dto.go`. `getWalChainBrokenReason` keeps its archive progress point check, because a segment still being uploaded also looks like a gap. `HasCompletedFullBackup` is read from the coverage having a latest restorable moment, so `GetNewestCompletedFullWithGaps` and its `FullBackupWithGaps` type lose their last caller and go. The gaps come from the segments the latest reach already read, through the helper `FindWalGapsInChain` now shares, so the request makes no extra query for them. The response gains a top-level `latestRestorableAt *time.Time` and `restorableRanges []{from, to}` in UTC, never null, with a Swagger description. Neither is part of `health`, because neither is a verdict.++Alternatives rejected:++- *Computing the moment in `wal_health` from the samples.* Samples know the archive progress point but not the backups or the gaps. The verdict would grow a second notion of "restorable" that could drift from the restore.+- *Calling `ResolveRestoreSet(databaseID, nil)` as it is.* It also reads every history file of the database on each refresh, and it returns the whole restore set only to take one time out of it.+- *Deriving the moment in the frontend from the Backups tab's list.* The list is paged, and its WAL ranges do not say which chain a restore would pick.+- *Using `current.lastArchivedWalAt`.* It is the newest archived segment, including segments after a gap, so it overstates what can be restored exactly in the case the tab must get right.+- *Filtering bridged gaps inside `FindWalGapsInChain`.* The Backups tab marks every gap of the history, bridged or not, and the test helper `WaitForWalGap` waits for any gap.+- *Showing a bridged gap as a notice.* The user asked for it as a picture rather than as one more line of text; D10 draws it.++### D2. One pure function composes the banner++`getVerdictBanner` takes the statistics, the time of the last successful refresh and `now`, and returns the whole banner:++- the tone and icon, unchanged;+- the headline: a new healthy key for the healthy verdict, the title of the most severe reason for needs attention and broken, and today's keys for collecting data, not streaming and the unconfirmed state;+- the headline reason's two sentences, from `getReasonTexts`;+- the other reasons, broken first, each as title plus two sentences;+- the restore sentence as `LocalizedText`, chosen by the four cases of the spec, for every verdict including collecting data.++The full backup button is not part of the banner; D3 decides it in a function of its own.++The "only up to" sentence follows the `WAL_CHAIN_BROKEN` reason alone. Since D1 the reason is listed only for a gap the latest restore cannot cross, so the moment is then always below the newest archived segment. The first version also compared the moment with `current.lastArchivedWalAt`, because the reason stayed listed after an incremental bridged the gap; that comparison and its comment go.++When the age of the moment cannot be computed, the sentence uses a variant without the age instead of showing "NaN d NaN h" (D12).++While the full backup button is visible, the banner component leaves out the headline reason's "what to do" sentence, because the button is that action. A user who cannot manage the database still reads it. The broken chain's "what happened" sentence is rewritten so it no longer repeats its title. The "Measured … ago" indicator moves into the headline row, and the text column keeps `max-w-3xl` (D11).++The reasons' order uses the existing `sortReasonsBrokenFirst`, which keeps the API order within one level. The restore moment formats as a local time for today and a local date and time otherwise, through the user's clock format (`shared/time`), followed by its age from `getRoundedDuration`.++`MonitoringReasonsComponent` is deleted. Its reason rendering moves into the banner as a compact list, and its notice rendering moves into the tips section (D5).++Alternatives rejected:++- *Keeping the reasons list under the banner and only changing the headline.* The headline would repeat the first list item, which is the duplication the change removes.+- *A headline per verdict level with reworded labels.* "Something is broken" stays vague whatever the wording; only the reason knows what broke.++### D3. The full backup button reuses the existing trigger, without a dialog++`DatabaseComponent` passes `isCanManageDBs` to `WalStreamMonitoringComponent`. The tab holds one flag, `isRequestingFullBackup`. A pure function returns the action from the level, whether the state is confirmed, the reasons, `latestRestorableAt`, `health.isFullBackupPending`, `isCanManageDBs` and that flag:++- hidden when the user cannot manage the database, when the verdict is not streaming or collecting data, when the state is unconfirmed, or when no broken chain, no missing slot and no lack of a full backup calls for it;+- hidden while the statistics report a full backup requested or running, because the reason's or the restore sentence's text then says that one is on its way;+- requesting while the flag is set;+- available otherwise.++`FullBackupAction` therefore holds three values: hidden, requesting and available. The tab passes the result to the banner component next to the banner.++The request flow lives in `FullBackupRequestController` in `<mon>/lib`, a class without React state like `WalStreamRefreshController`, so vitest covers it with an injected request, refresh and reporters. The no full backup case is read from `latestRestorableAt` being null, so it needs no notice. The button calls `physicalBackupsApi.triggerPhysicalBackup(database.id, 'full')`. The backend stores the request before it answers, so on success the tab calls `WalStreamRefreshController.retry()`, and the next response reports the full backup pending. The flag clears when the refresh after a success lands, and a scheduled refresh that lands while the request is still being sent leaves it set. On failure the flag clears at once, `translateApiError` shows through `message.error`, and the action falls back to available.++Alternatives rejected:++- *A link to the Backups tab.* It adds a step and a context switch for the one action the banner exists to offer.+- *A confirmation dialog.* A full backup destroys nothing, and the Backups tab starts one without a dialog. Two different flows for the same request would surprise.+- *Hiding the button behind a "fix it" menu.* There is exactly one fix.++### D4. Four figure cards replace the stage cards in the main area++A pure function `getMonitoringFigures(statistics)` in `<mon>/lib` returns null for the collecting data and not streaming verdicts, and otherwise the three figures as values a component formats, each value null when unknown so the component renders "not measured". The figures row shows the last save as `formatRelativeTime(current.lastArchivedWalAt)`, the amount waiting to be saved from `keepingUp.unarchivedWalBytes`, and the write and save rates from `keepingUp.sourceWriteBytesPerSecond` and `keepingUp.archiveBytesPerSecond`. The amounts are taken from `keepingUp` rather than `current` so the figures and the keeping-up sentence underneath agree. Numbers ease with `useEasedTransition`, as the stage cards do today. The figures sit in four cards, `grid grid-cols-2 lg:grid-cols-4`, each with a muted `text-sm` label and a `text-xl font-semibold tabular-nums` value: last change saved, waiting to be saved, database writes and saved to storage. The first version put both rates in one slot as a sentence, "27.3 KB/s written, 27.3 KB/s saved", which read as text rather than a number and repeated the caption. The two rate cards reuse the chart's `charts.databaseWrites` and `charts.savedToStorage` labels and show a dot in the chart line's color; `figures.speed` and `figures.speedValue` go. Apart from those dots the figures use the AntD text colors only. The keeping-up sentence and its consequence sentences move from the banner to the caption under the figures. The unknown state renders no sentence.++Alternatives rejected:++- *Coloring a figure by the reasons about it.* It would add a second severity signal next to the banner, which is how the red storage card ended up contradicting its own text.+- *Keeping the three stage cards in the main area.* Their progress bars against the rebuild lag and the pause size are engineering limits a junior cannot act on.+- *AntD `Statistic`.* Its title and value styling fits a KPI dashboard and ignores the eased value. A small grid of Tailwind cards is less code.++### D5. Technical details are an open section, with the tips inside++The first version hid tips and technical details in two AntD `Collapse` panels closed by default. Readers had to click to see the numbers that explain the verdict, and "Tips: 1" said nothing about what the tip was. The technical details are now a plain `section` under the main chart, separated by a border and headed "Technical details": the path of changes, then the tips, then the two secondary charts and the raw values table. Tips list the notices except `NO_FULL_BACKUP_YET` as quiet notes, each an info icon with the notice's title and two sentences in neutral text; the "Tips: {{count}}" title goes. The charts now render in a visible container from the start, so the recharts warning about a zero-sized container also goes.++Alternatives rejected:++- *A separate "Advanced" tab.* A fourth tab for detail of the third splits one subject across two places.+- *Tooltips instead of a details section.* Raw values need to be read and copied, not hovered.++### D6. Chart rules as pure functions++`<mon>/lib/chartRows.ts` gains:++- `hasEnoughChartPoints(series)`: at least four points with values, replacing `hasAnyChartValues`;+- `getChartTimeDomain(series)`: from the first point with values, or from `series.from` when the data covers the whole period, to `series.to`;+- `getBinaryAxisTicks(dataMaximum, minimumTop)`: round ticks for the amount axis, replacing the first version's `getAmountAxisMaximum`. It picks the unit `1024^k` of the larger of the two values, then a step of 1, 2, 2.5 or 5 × 10^n in that unit for about four intervals, and ends on a multiple of the step. 1 MiB gives 0, 256 KB, 512 KB, 768 KB and 1 MB. Recharts' own ticks are decimal while `formatBytes` is binary, which is how "293 KB/s, 585.9 KB/s, 878.9 KB/s" ended up on the axis. The Y axis gets these `ticks` and `domain={[0, last tick]}`;+- `getMissingDataRanges(series)`: runs of two or more points without values after the first point with values. The chart shades each with a `ReferenceArea`, and a caption says "No measurements from … to …" for up to three of them.++The chart header holds the title and an HTML legend on the left and, for the main chart, the period `Segmented` on the right, replacing recharts' centered `Legend`. The plots have fixed heights, 260 px for the main chart and 200 px for the technical charts: the tab has a maximum width (D11), so a height that grows with the window would only make the charts taller than the tab is wide in proportion. The saved-to-storage line becomes a wide translucent band (`strokeWidth` 6, `strokeOpacity` 0.35) under the thin database writes line, so the two stay distinguishable when they are equal, which is the healthy case.++The minimum tops are 64 KiB/s for the rate chart and `current.walSegmentSizeBytes` for the two amount charts, or 16 MiB when no sample exists yet. `getDataSinceMs` keeps driving the "Data since" caption. The empty state's text changes to "Not enough data for this period yet", with the hint that a shorter period may already have a chart.++Alternatives rejected:++- *A time threshold such as 10 minutes of data.* The week view's 28-minute buckets would need more than two hours for four points, and a message promising 10 minutes would be false.+- *Keeping the full-period axis.* Two minutes of data then fill 3% of the width.+- *A logarithmic amount axis.* It reads poorly for this audience, and it distorts the gap between writes and saves, which is the chart's point.+- *recharts `ResponsiveContainer aspect`.* It has no maximum height in every version we ship, so a 2K screen would get a very tall chart. A fixed height class renders into static markup a test can check.++### D7. Stage colors and arrows in the path of changes++`REASON_STAGES` becomes `Record<WalStreamReasonCode, PathStage | null>` with `WAL_CHAIN_BROKEN` mapped to null, and `getStageTones` skips null stages. Each arrow puts the responsive classes on a wrapper `span` and leaves the icon unstyled, so AntD's icon rule cannot override them.++Alternatives rejected:++- *Mapping the broken chain to the source stage.* The source is fine; the gap is in the history Databasus holds.+- *One rotating arrow icon.* It works too, but a transform is harder to read in the markup than two wrappers.++### D8. Strings++New keys cover the healthy headline, the four restore sentences, the full backup button and its success message, the three figure labels and "not measured", the tips title, the technical details title and the new empty chart text. `monitoring.levels` keeps its texts, because the unconfirmed state names the last known level with them. The keys only the deleted blocks used are removed: the keeping-up unknown sentence and the old empty chart text. The follow-up adds the restore timeline's title, segment names and lost-stretch sentence, the restore sentence without an age, and the missing measurements caption; it rewrites the broken chain's "what happened" sentence and removes `figures.speed` and `figures.speedValue`. The width follow-up adds the restore sentence from the start of the newest restorable stretch, with and without an age, and removes the tips title. Every key lands in all six dictionaries, written in each language rather than translated word for word.++### D9. Tests++- Backend: controller tests in `controllers/physical/controller_test.go` for the restorable moment without gaps, with a gap in the newest chain, with an incremental backup completed after the gap, with a full backup and no WAL, and without a full backup. The split of `ResolveRestoreSet` stays covered by the existing `chain_view` tests.+- Backend, restore coverage: `chain_view` tests for `GetRestoreCoverage` with no full backup, contiguous WAL, a gap without an incremental, a gap bridged by a completed incremental, an incremental before the gap, a failed, chain-broken or running incremental after the gap, two gaps with only the first bridged, an incremental whose stop LSN falls into a missing segment, a segment still uploading, and a newer full backup. Every case also checks that the last range ends at the latest restorable moment. Controller tests run the verdict with a streamer and samples: a bridged gap is healthy with two ranges (written first and run against the old code, where it fails with the broken chain), a gap after the newest incremental is broken, a failed incremental after the gap is broken, and no full backup gives empty ranges. The response format check also covers `restorableRanges`.+- Width follow-up: a backend test that a progress point past the probed position gives zero unsaved, written first and failing on the old code; vitest for the restore sentence naming the newest stretch's start, the plain sentence for one stretch, the overlay moving the restore point with the live save and keeping it where a gap stopped it; static markup for the open technical details with their heading and the tips shown as notes.+- Frontend, follow-up: vitest for `getBinaryAxisTicks`, `getMissingDataRanges`, `getRestoreTimeline` and non-finite durations, and static-markup tests for the four figure cards, the timeline's lost-stretch sentence, and the "what to do" sentence hidden next to the button and shown without it.+- Frontend: vitest for the banner composition, the restore sentence cases, the full backup action states, the figures, the chart rules and the stage tones. Static-markup tests in `WalStreamMonitoringSections.test.tsx` for the healthy and broken banners, the absent button for a read-only user, the technical details body, the chart captions, and each arrow icon sitting in a wrapper that carries its breakpoint class while the icon carries none. Static markup cannot apply CSS breakpoints, so the test pins the markup that makes them work.++### D10. The restore timeline++`<mon>/lib/restoreTimeline.ts` exports `getRestoreTimeline(ranges, now)`. It returns the segments of one bar from the first range's start to `now`: restorable for each range, lost for each stretch between two ranges, and not saved yet for the tail from the last range's end to `now`. Each segment carries its start and end and its position in percent, and a lost segment keeps a minimum width, so a gap of a few hours stays visible on a chain months long. `RestoreTimelineComponent` draws the bar from plain divs between the figures and the main chart, with green for restorable, hatched red for lost and gray for not saved yet, the two edge dates under the bar, an AntD `Tooltip` on each segment, and one sentence per lost stretch, up to three. It renders nothing without ranges.++Alternatives rejected:++- *A recharts chart.* One bar with three kinds of segment needs no axes, and divs keep the meaning in text a static-markup test can read.+- *Every chain of the database.* The ranges describe the newest chain, which is what a restore to the latest point uses; older chains stay on the Backups tab.++### D11. Wide screens++The first version kept the page width, like the Config and Backups tabs, and let the plots grow with the window. At 2560 px everything read as too large, so the tab's card now stops at `max-w-6xl` (1152 px) and stays left-aligned under its tab button. Below that width nothing changes; above it the tab keeps its laptop proportions. The banner's text column keeps its own maximum width, the figures sit in cards, the values use `text-xl`, and the plots keep fixed heights (D4, D6).++The path of changes decides its layout by its own width with a Tailwind container query (`@container` on a wrapper, `@4xl:` on the grid and the arrow wrappers) rather than by the window: the sidebar and the tab's maximum width decide how much room it gets, so at 1240 px the stages stack with downward arrows instead of squeezing three stages and two connectors into about 800 px.++Alternatives rejected:++- *Centering the capped card.* The tab buttons sit on the left, and a centered card would detach from them.+- *Viewport breakpoints for the pipeline.* The section is 400 px narrower than the window, so a viewport rule either squeezes the stages at 1240 px or stacks them at 1440 px.++### D12. Invalid durations++`getSecondsBetween` in `<mon>/lib/roundedDuration.ts` returns null when either time cannot be read, and its callers leave the age out: the restore sentence switches to a variant without it, and the measured label falls back to "not measured yet". The duration helpers stay as they are, because every number they receive comes from a time difference or from the API's estimates. "NaN d NaN h ago" appeared on a live screen while a frontend that already expected `latestRestorableAt` ran against a backend started before the field existed: `dayjs(undefined)` printed the current time and `new Date(undefined)` gave NaN. One image ships both halves, so production cannot meet that mismatch; the guard only keeps an unreadable time from reaching the screen.++### D13. Current values every second, from the running streamer++The tab asked for numbers that move in about real time, while samples are taken every 30 seconds. Taking them every second would multiply the stored rows and the source connections by 30 and change the meaning of the rate formulas and the thresholds that count samples. Instead the stored sample stays as it is, and a new endpoint reads the running streamer:++- `WalStreamSupervisor` in `usecases/physical/postgresql` remembers its newest slot probe with its time, from the 10-second liveness watcher and the 30-second sampler alike, and exposes `GetLiveState(now)`. That reads the local queue from the watch directory, the pause size and the receiver flag from their atomics, and the newest committed segment from the catalog, then derives the archive progress point and the unsaved amount exactly as the sample does. It never consumes the upload snapshot or the restart counters, which reset on read.+- `PhysicalWalStreamSupervisor` keeps each running supervisor on its `runningStreamer` and answers `GetLiveState(databaseID)`; the deployment runs in one process, so the HTTP handler and the streamer share memory.+- `GET /backups/physical/database/:id/wal-stream/live` authorizes like the statistics and answers `isStreamerRunning` with the values, or without them.+- The frontend's `WalStreamLiveController`, a class like `WalStreamRefreshController`, reads it every second while the browser tab is visible. A failed reading keeps the statistics' values. The tab overlays the newer live values onto `current` and the unsaved amount before the figures, the restore timeline's end and the path of changes read them; the verdict, the rates and the charts keep the 30-second statistics.+- While the statistics' `latestRestorableAt` equals their `current.lastArchivedWalAt`, the restore reached the newest save and no gap lies ahead, so the overlay moves `latestRestorableAt` and the end of the newest restorable range to the live `lastArchivedWalAt`. Without that, the banner named a moment up to 30 seconds older than the "last change saved" figure next to it. A restore stopped short of the newest save stays where the statistics put it; a new gap appearing between two refreshes shows within one statistics refresh.+- The source probe can be up to 10 seconds old while segments keep landing, so the archive progress point may pass the probed position. The live unsaved amount is then zero, not unknown: everything the source had written by the probe is saved. Reporting it as unknown made the figure flicker to "not measured" after every saved segment.++Alternatives rejected:++- *Sampling every second.* 30 times the rows and the source connections, and the rate formulas assume one interval for all rows.+- *A one-second source probe on a held connection.* Fresher source values, but a second long-lived connection per database; the user chose the 10-second probe.+- *Server-sent events.* The backend has no streaming endpoint, and a one-second poll is as fresh for one reader.++### D14. The path of changes as a flow strip++The first version drew three cards with thick borders in the healthy color, a progress bar that looked broken at 0 B, and small arrows with the rate floating between them. The second drew three neutral cards with a large "0 B" over an empty meter in two of them and the rates above loose arrows; readers asked why everything was 0 B while the speed was 54 KB/s. Both values were right: the rate is the 10-minute average of the keeping-up window, the amount is the current queue, and a database that writes in bursts empties its queue within seconds. The strip now says so and stops drawing an empty queue as a number:++- One frame holds a five-column grid, stage, link, stage, link, stage, whose cells span its two rows through `grid-rows-subgrid`: the icons, titles and lines share the first row, the details and link names the second. A container query (`@2xl:`) on the frame's content decides between the row and the stacked layout.+- Each stage has a round icon, neutral or in the tone color with a problem, its name, the level icon and word with a problem, and a line running from the title to the next link, so the strip reads as one pipe. Each link carries its rate as a pill on that line, ending in an arrowhead, and its chart name and color under it.+- `PathAmountComponent` shows "nothing waiting" with a success icon for an empty queue, and a number with "X of Y" over a thin meter otherwise. The rebuild and pause limit sentences appear only for a queue above zero; the allowance sentence only when the source sets a limit, because the no slot WAL limit tip already says when it does not.+- The storage stage shows the last save and the unsaved amount under it.+- A caption under the strip says that rates are averages over the last 10 minutes and amounts are right now, and the two rate cards above say "avg. 10 min" next to their labels.++## Risks / Trade-offs++- [The latest reach reads the newest chain's WAL segments on every statistics request, every 30 seconds per open tab.] → The gap check used to make that read on its own; it now reuses the reach's segments, so the request makes the same number of segment reads as before this change.+- [Every open tab reads the current values every second.] → The reading touches memory, the watch directory and one indexed catalog query, opens no source connection, and stops while the browser tab is hidden.+- [The restorable ranges walk every WAL segment of the newest chain on each request.] → One backward pass and a binary search per anchor keep it at O((segments + anchors) · log segments), over rows the latest reach reads anyway.+- [The restorable moment is the time Databasus received a segment, a little after the last change inside it.] → It is the moment the restore accepts as a target, so the screen never promises more than the restore delivers.+- [The week view shows no chart for about the first two hours of streaming.] → The empty state says that a shorter period may already have one.+- [Removing the reasons list changes the layout existing users know.] → The tab was added by the `wal-stream-monitoring-tab` change, archived on 2026-10-19, so few users know it yet.++## Migration Plan++No migration. The API field is additive, and the backend and frontend ship in one image. Rolling back the image restores the previous tab and drops the field.diff --git a/openspec/changes/archive/2026-10-21-rethink-wal-monitoring-tab/proposal.md b/openspec/changes/archive/2026-10-21-rethink-wal-monitoring-tab/proposal.mdnew file mode 100644index 00000000..96eea76b--- /dev/null+++ b/openspec/changes/archive/2026-10-21-rethink-wal-monitoring-tab/proposal.md@@ -0,0 +1,68 @@+## Why++The Monitoring tab of a WAL-streaming database answers an engineer's question, "where are the bytes right now", while the people who open it ask "can I restore my database, to which moment, and what do I do if I can't". Juniors, self-hosters and freelancers make up most of these users. The answer is on the screen, but they have to assemble it from six blocks, and some of those blocks contradict each other.++A broken chain shows the problem on the tab today:++- The headline says "Something is broken" without naming what broke. Under it sits "The database writes almost nothing; new changes reach storage within minutes", which reads as good news.+- The storage card turns red while it says "Last change saved a few seconds ago".+- The notice about a missing limit, which appears on almost every installation because PostgreSQL sets no limit by default, takes a box as large as the failure itself.+- Three charts fill the hour axis even when only two minutes of data exist. Their axes auto-scale to 0-100 B, so noise looks like a signal.+- Nothing on the tab says to which moment the backups can restore, although that is the reason anyone turns on WAL streaming.++## What Changes++- The statistics API gains the latest moment the backups can restore to right now. It is the same moment a restore to the latest available point reaches, so the tab and the restore can never disagree. It is empty while no full backup has completed.+- The statistics API also gains the stretches of time the newest chain can restore to, so the tab can draw a WAL gap that an incremental backup later bridged.+- The broken chain reason is listed only for a gap the latest restore cannot cross. Today a gap that a completed incremental backup bridged keeps the verdict broken: a live database showed "Changes were lost between backups" in red next to a correct "You can restore … up to 3:17 PM".+- The tab is rebuilt from the simple answer down to the detail:+ - **Verdict banner.** The headline names the most severe problem, or says that all changes are being saved. The banner always says to which moment the database can be restored. When the fix is a full backup, the banner offers a button that starts one, to users who may start backups. Other problems appear as short lines inside the same banner, so there is no separate reasons list that repeats it.+ - **Four current figures** in cards: when the last change was saved, how much is waiting to be saved, how fast the database writes and how fast Databasus saves. The keeping-up sentence moves out of the banner and becomes the caption of these figures, so it no longer appears under an unrelated failure.+ - **Restore timeline**: one bar from the start of the newest chain to now that marks which stretches can be restored and which cannot, with a sentence for each stretch that cannot.+ - **One chart**: database writes against saved to storage, for the last hour, day or week. It appears only once there is enough data to read, its time axis starts where the data starts, and its amount axis has a minimum scale and round ticks, so a quiet database does not look busy. It keeps a fixed height, keeps equal lines distinguishable, and shades and names stretches without measurements.+ - **Technical details**: one open section under the chart with the path of changes from the database through Databasus to storage, the tips as quiet notes, the "not saved yet" and buffer charts, and the raw values. The no full backup yet notice is no longer a tip, because the banner's restore sentence says it.+- The tab stops growing at about 1150 px, so a 2K screen shows it at laptop proportions.+- The path of changes stops coloring a stage for a broken chain. A broken chain is a problem of the backup history, not of any stage. Each arrow between stages shows one direction instead of both.+- The tab reads the running streamer's current values every second through a new endpoint, so the buffer, the unsaved amount and the last save move in about real time. Values from the source database follow the streamer's existing probe, at least every 10 seconds. The verdict, the rates and the charts keep refreshing every 30 seconds.+- The path of changes in the technical details becomes a pipeline: neutral stages with a large main number, "X of the limit" next to a thin meter, a problem shown by icon and word, and connectors that carry the rates.+- **BREAKING** for the tab layout only. The standalone reasons list and the large notice box are deleted, not kept as an alternative view. The API change is additive: two new fields in the statistics response, `latestRestorableAt` and `restorableRanges`, and a new endpoint, `GET /backups/physical/database/:id/wal-stream/live`, for the current values; no field is removed or renamed.++## Capabilities++### New Capabilities++None.++### Modified Capabilities++- `physical-backups/wal-stream-monitoring`: the API response gains the latest restorable moment and the restorable stretches; the broken chain reason ignores gaps a completed incremental bridged; the requirements for the Monitoring tab's verdict, keeping-up explanation, path of changes and charts change to the layout above; the tab gains the full backup action, and the tips move into the technical details.++## Impact++- Backend:+ - a read of the restore coverage in the chain view, built from the same code that resolves a restore to the latest point: the latest restorable moment, the restorable stretches and the gaps the latest restore cannot cross;+ - the verdict receives only those gaps;+ - two new fields in the statistics response, their Swagger annotation and regenerated Swagger docs;+ - the WAL stream supervisor remembers its newest source probe and answers `GetLiveState`, and `PhysicalWalStreamSupervisor` keeps each running supervisor reachable by database;+ - the endpoint `GET /backups/physical/database/:id/wal-stream/live` with its Swagger annotation;+ - chain view, live state and controller tests for the coverage, the verdict and the current values.+- Frontend:+ - the monitoring slice under `features/backups/physical/monitoring`: the banner, the figure cards, the restore timeline, one main chart, the tips and technical details sections, and the existing path of changes moved into technical details;+ - the database page passes whether the user may manage databases to the tab, which needs it for the full backup button;+ - the API model type gains the new fields, and new models and an API method cover the current values;+ - a controller reads the current values every second while the browser tab is visible, and the tab lays them over the statistics;+ - new and changed strings in all six interface dictionaries, with the strings the deleted blocks used removed.+- Database load: unchanged in reads of WAL segments. The restore coverage reads the newest chain's segments once, and the verdict's gaps come from the same rows instead of a read of their own.++## Out of scope++- Changes to the verdict's other reasons, their thresholds, the keeping-up summary or the sampling. The broken chain reason changes only in which gaps it counts.+- The write and save rates jumping between a value and zero on a database that writes in bursts. The 10-minute window averages the samples it has; smoothing it is a separate change.+- The Backups tab's backup list being requested every few seconds while the Monitoring tab is open.+- New notifications.+- Restoring from the Monitoring tab. The restore stays on the Backups tab.+- A monitoring summary in the database list or in the sidebar card.+- The disagreement between the sidebar's "Unavailable" healthcheck badge and the streaming source's reachable state. It is a separate problem of the healthcheck.+- Charts for periods other than the last hour, day and week, or zoom on a chart.+- Starting an incremental backup from the tab.+- Other physical backup modes and logical databases, which have no Monitoring tab.diff --git a/openspec/changes/archive/2026-10-21-rethink-wal-monitoring-tab/specs/physical-backups/wal-stream-monitoring/spec.md b/openspec/changes/archive/2026-10-21-rethink-wal-monitoring-tab/specs/physical-backups/wal-stream-monitoring/spec.mdnew file mode 100644index 00000000..d30b7862--- /dev/null+++ b/openspec/changes/archive/2026-10-21-rethink-wal-monitoring-tab/specs/physical-backups/wal-stream-monitoring/spec.md@@ -0,0 +1,667 @@+## ADDED Requirements++### Requirement: The statistics state what the backups can restore++The statistics SHALL state the latest moment to which the database's backups can restore it at the time of the request. That moment SHALL be the one a restore to the latest available point reaches. It starts from the newest completed backup of the newest chain, full or incremental, and extends through the WAL that follows that backup without a gap. With WAL after that backup, it is the time Databasus received the last segment before the first gap after that backup, or the newest segment when there is no such gap. Without WAL after that backup, it is the backup's completion time. When no full backup has completed, the statistics SHALL state that no moment can be restored yet.++The statistics SHALL also state the stretches of time the newest chain can restore to, oldest first. Each completed backup of that chain, full or incremental, opens a stretch from its completion time to the moment the WAL after it reaches without a gap, by the same rule as above. Stretches that overlap or touch SHALL be merged. A WAL segment that is still being uploaded SHALL end a stretch like a gap. The last stretch SHALL end at the latest restorable moment. Without a completed full backup, the list SHALL be empty.++#### Scenario: Streaming without gaps++- **WHEN** the newest full backup completed yesterday and every WAL segment since then is archived without a gap+- **THEN** the latest restorable moment is the time Databasus received the newest archived segment++#### Scenario: Gap in the newest chain++- **WHEN** the slot was rebuilt at 07:51, which left a WAL gap after the segment received at 07:50, no backup completed after the gap, and segments after the gap keep arriving+- **THEN** the latest restorable moment is 07:50+- **AND** a restore to the latest available point reaches the same moment++#### Scenario: Incremental backup after the gap++- **WHEN** the newest chain has a WAL gap at 07:51, an incremental backup of that chain completed at 09:00, and every segment after 09:00 is archived without a gap+- **THEN** the latest restorable moment is the time Databasus received the newest archived segment+- **AND** the restorable stretches are two: from the full backup's completion to 07:50, and from 09:00 to the newest archived segment++#### Scenario: Incremental backup before the gap++- **WHEN** an incremental backup of the newest chain completed at 06:00, and the chain has a WAL gap at 07:51 with segments after it+- **THEN** the latest restorable moment is the time Databasus received the last segment before the gap+- **AND** the restorable stretches are one, from the full backup's completion to that moment++#### Scenario: Newer full backup++- **WHEN** an older chain has a gap, and a newer full backup completed after it+- **THEN** the restorable stretches start at the newer full backup's completion++#### Scenario: Full backup without WAL after it++- **WHEN** the only completed full backup finished at 14:02 and no WAL segment followed it+- **THEN** the latest restorable moment is 14:02++#### Scenario: No full backup yet++- **WHEN** no full backup of the database has completed+- **THEN** the statistics state that no moment can be restored yet+- **AND** the restorable stretches are empty++### Requirement: The Monitoring tab says to which moment the database can be restored++The verdict banner SHALL say, in one sentence, to which moment the database can be restored:++- when a moment is known and the WAL chain broken reason is listed: until a new full backup finishes, the database can be restored only up to that moment;+- when a moment is known, that reason is not listed and the newest restorable stretch covers the whole history: the database can be restored to any moment up to that moment;+- when a moment is known, that reason is not listed and an earlier stretch cannot be restored: the database can be restored to any moment from the start of the newest restorable stretch up to that moment, so the sentence never promises the moments the timeline marks as lost;+- when no moment can be restored yet and a full backup is requested or running: nothing can be restored until the first full backup finishes, which is on its way;+- when no moment can be restored yet and no full backup is requested or running: nothing can be restored yet, because no full backup has finished.++The moment SHALL be shown as a local time for today and as a local date and time otherwise, followed by how long ago it was, rounded for reading. When that age cannot be computed, the sentence SHALL leave it out instead of showing an invalid number. The sentence SHALL appear for every verdict, collecting data included, and SHALL keep the last known moment while the current state cannot be confirmed.++#### Scenario: Healthy database++- **WHEN** the verdict is healthy and the latest restorable moment was 30 seconds ago+- **THEN** the banner says that the database can be restored to any moment up to that time, 30 seconds ago++#### Scenario: Broken chain++- **WHEN** the WAL chain broken reason is listed, the latest restorable moment is 07:50 today and the newest segment was archived at 07:58+- **THEN** the banner says that until a new full backup finishes, the database can be restored only up to 07:50++#### Scenario: Broken chain repaired by an incremental backup++- **WHEN** an incremental backup after the gap brought the latest restorable moment up to the newest archived segment+- **THEN** the WAL chain broken reason is not listed+- **AND** the banner says that the database can be restored to any moment up to that moment++#### Scenario: Old gap before the newest restorable stretch++- **WHEN** the database cannot be restored to moments between Oct 10 18:35 and Oct 20 07:51, and can be restored to every moment after that up to 08:32 today+- **THEN** the banner says that the database can be restored to any moment from Oct 20 07:51 up to 08:32++#### Scenario: Just enabled++- **WHEN** the verdict is collecting data and no full backup has completed or is requested+- **THEN** the banner says that nothing can be restored yet because no full backup has finished++#### Scenario: Saving stuck++- **WHEN** no new changes have reached storage for 40 minutes while the database keeps writing+- **THEN** the restore sentence names a moment about 40 minutes ago++#### Scenario: Before the first full backup++- **WHEN** no full backup has completed and none is requested or running+- **THEN** the banner says that nothing can be restored yet because no full backup has finished++### Requirement: The Monitoring tab offers to start a full backup when that is the fix++When a full backup is what repairs the situation, the verdict banner SHALL offer a button that starts one. That is the case while all of these hold:++- the verdict is healthy, needs attention or broken, and the current state is confirmed;+- the WAL chain broken reason or the slot missing reason is listed, or no full backup has completed;+- no full backup is requested or running.++The not streaming verdict SHALL never offer the button, because Databasus takes no backups while streaming is off. The collecting data verdict SHALL not offer it either: it lasts at most two minutes, and the restore sentence already says whether a first full backup exists.++The button SHALL request a full backup at once, the same way the Backups tab does. While the request runs, the button SHALL show that it is working and SHALL not accept another click. After the request succeeds, the tab SHALL refresh at once, so the banner says that a full backup is on its way without waiting for the next scheduled refresh. A failed request SHALL show the error and leave the button available.++#### Scenario: Broken chain fixed from the tab++- **WHEN** a user who may manage the database sees the WAL chain broken reason with no full backup pending, and presses the button+- **THEN** a full backup is requested+- **AND** the banner says that a full backup is on its way++#### Scenario: Full backup already pending++- **WHEN** the WAL chain broken reason is listed and a full backup is requested or running+- **THEN** the banner offers no button+- **AND** says that a new full backup is on its way++#### Scenario: Request refused++- **WHEN** the full backup request fails+- **THEN** the tab shows the error+- **AND** the button can be pressed again++#### Scenario: Missing slot++- **WHEN** a user who may manage the database sees the slot missing reason with no full backup pending+- **THEN** the banner offers the full backup button++#### Scenario: Healthy streaming before the first full backup++- **WHEN** the verdict is healthy, no full backup has completed and none is requested or running+- **THEN** the banner offers the full backup button++#### Scenario: Streaming off++- **WHEN** the verdict is not streaming because backups are disabled, and no full backup has completed+- **THEN** the banner offers no full backup button++### Requirement: Only users who may manage the database can start a full backup from the Monitoring tab++The full backup button SHALL be shown only to users who may manage the database's backups. A user who can only view the database SHALL see the problem and the sentence about what to do, without the button. A full backup request from such a user SHALL be refused by the API, whatever the tab shows.++#### Scenario: Read-only member++- **WHEN** a workspace member who can view but not manage the database opens the tab while the chain is broken+- **THEN** the banner shows the problem and what to do+- **AND** offers no full backup button++#### Scenario: Request without permission++- **WHEN** a user who cannot manage the database requests a full backup through the API+- **THEN** the request is refused+- **AND** no full backup is requested++### Requirement: The Monitoring tab shows the current flow as four figures++Under the verdict banner, the tab SHALL show four figures from the newest statistics, each as a label with a large value:++- when the last change was saved to storage, as a relative time, or that nothing is saved yet;+- how much is waiting to be saved to storage;+- how fast the database writes changes;+- how fast Databasus saves them.++The two rates SHALL use the same names and colors as the lines of the main chart, so a reader can match a figure to its line, and SHALL say that they are averages over the last 10 minutes, so a rate next to an empty queue does not read as a contradiction.++The figures SHALL be shown for the healthy, needs attention and broken verdicts, and while the current state cannot be confirmed, and not for the collecting data and not streaming verdicts. A value that is not known SHALL be shown as not measured, not as zero.++#### Scenario: Busy healthy database++- **WHEN** the database writes 10 MB/s, Databasus saves 10 MB/s, 20 MB is not saved yet and the newest segment was archived 15 seconds ago+- **THEN** the figures show 15 seconds ago, 20 MB, 10 MB/s of database writes and 10 MB/s saved to storage++#### Scenario: No write rate yet++- **WHEN** the window of the last 10 minutes holds no sample with a source write value+- **THEN** both rate figures say not measured++### Requirement: The Monitoring tab shows tips and technical detail below the chart++Notices other than the no full backup yet notice SHALL appear as tips: quiet notes, each with its title and two sentences, inside the technical details section under the path of changes. The no full backup yet notice SHALL be shown only through the banner's restore sentence, which appears for every verdict. A tip SHALL never use a warning or error color. The no slot WAL limit tip SHALL explain in plain words what the limit protects and what it costs.++Everything else SHALL sit in one technical details section below the chart, with its own heading and shown without a click: the path of changes, the tips, the chart of what is not saved and not received yet, the buffer chart, and the raw values.++#### Scenario: Default source settings++- **WHEN** the source sets no limit on WAL kept for the slot and nothing else is wrong+- **THEN** the technical details section shows one tip with its text++#### Scenario: Engineer looks for raw values++- **WHEN** a reader scrolls below the main chart+- **THEN** the technical details section shows the path of changes, the two additional charts and the raw values++### Requirement: The Monitoring tab shows which moments can be restored++Under the figures, the tab SHALL show a timeline of the newest chain, from the start of its first restorable stretch to now. The timeline SHALL mark the restorable stretches, the stretches between them that cannot be restored, and the time after the latest restorable moment that is not saved yet, in different colors and patterns. A stretch that cannot be restored SHALL stay visible however short it is compared with the whole timeline. Under the timeline, the tab SHALL name each stretch that cannot be restored, up to three, in a sentence with its start and end, so color is not the only signal. The timeline SHALL not appear when the statistics list no restorable stretch.++#### Scenario: Old gap bridged by an incremental backup++- **WHEN** the newest chain cannot restore to moments between Oct 10 18:35 and Oct 20 07:51, and can restore to every moment after that up to a minute ago+- **THEN** the banner is green+- **AND** the timeline marks the stretch from Oct 10 18:35 to Oct 20 07:51 as not restorable+- **AND** a sentence under it says that the database cannot be restored to moments between those times++#### Scenario: No full backup yet++- **WHEN** no full backup has completed+- **THEN** the tab shows no timeline++### Requirement: The Monitoring tab reads well on wide screens++The tab SHALL stop growing at a maximum width of about 1150 px, so on wide screens the text, the figures and the charts keep the sizes they have on a laptop instead of stretching. The banner's text SHALL keep a readable line length, the figures SHALL sit in cards next to each other, and the charts SHALL keep a fixed height. The path of changes SHALL put its stages in a row only when its own section is wide enough for them, and stack them otherwise.++#### Scenario: 2560 px wide screen++- **WHEN** the tab is shown in a 2560 px wide window+- **THEN** the tab is no wider than in a 1600 px wide window+- **AND** the four figures sit in one row of cards++#### Scenario: Laptop screen++- **WHEN** the tab is shown in a 1240 px wide window next to the sidebar+- **THEN** the stages of the path of changes sit in one row without horizontal scrolling++### Requirement: The API serves the current values every second++A second authenticated endpoint SHALL return the current values of a database's running WAL stream, read from the running streamer at the time of the request and not stored: the time of the reading, the local queue and its pause size, whether receiving runs, the archive progress point, the time the newest WAL segment was archived, and how much is not saved to storage yet. The values from the source database, its current position, the slot's status, the slot lag and the remaining allowance, SHALL come from the newest probe of the source that the streamer already makes, at least every 10 seconds, together with the time of that probe; the endpoint SHALL not open a connection to the source itself. Only users who can view the database SHALL read it. While no streamer runs for the database, the response SHALL say so and carry no values.++#### Scenario: Buffer drains between two samples++- **WHEN** the local queue drains from 300 MB to 0 B within five seconds+- **THEN** a request one second later reports 0 B in the local queue++#### Scenario: Source values follow the probe++- **WHEN** the newest source probe ran 7 seconds ago+- **THEN** the source-side values are those of that probe, with its time++#### Scenario: Saving moves past the probed position++- **WHEN** segments reached storage after the newest source probe, past the source position it found+- **THEN** the response says that nothing is waiting to be saved, not that the amount is unknown++#### Scenario: Streamer not running++- **WHEN** WAL streaming is off for the database+- **THEN** the response says that no streamer runs and carries no values++#### Scenario: Member without access++- **WHEN** a user who cannot view the database requests its current values+- **THEN** the request is refused++## MODIFIED Requirements++### Requirement: The statistics state one health verdict with reasons++The statistics SHALL state one verdict:++- **not streaming**: WAL streaming is not expected to run, because the database is not in WAL streaming mode, its backups are disabled or it has no storage;+- **collecting data**: the streamer is not failing, no sample is newer than the current session's start, and that session started less than 2 minutes ago, or no streamer has started yet;+- **broken**: at least one reason applies at the broken level;+- **needs attention**: at least one reason applies at the needs-attention level and none at the broken level;+- **healthy**: no reason applies.++The first matching verdict in this order wins.++Each reason SHALL carry its code and its level. It SHALL also carry the time the condition began when that time is known, and the measured amount and the threshold it was compared with when the rule compares an amount. A needs-attention reason that is read from samples SHALL appear only when its condition holds in the two newest samples, so a single unusual sample does not change the verdict. Reasons whose rule already waits for a duration are exempt.++| Reason | Needs attention | Broken |+|---|---|---|+| Streaming stopped | - | the streamer has been failing for 1 minute or longer, or the newest sample is older than 2 minutes, and the newest sample did not find the source unreachable |+| Source unreachable | the newest sample found the source unreachable, and the source has been unreachable for 1 to 5 minutes since | the same for 5 minutes or longer, also when streaming stopped after that sample |+| WAL chain broken | - | the newest completed full backup's chain has a WAL gap below the archive progress point that the latest restore cannot cross, because no completed backup of that chain starts after the gap; it clears when a completed incremental backup of that chain or a newer full backup starts after the gap |+| Slot missing | - | the newest sample found the source without the slot |+| Slot lost | - | the newest sample reports the slot's status as `lost` |+| Archive not advancing | the archive progress point has stood still for 10 minutes or longer while the source keeps writing | the same for the archive staleness threshold of 30 minutes or longer, which is when the "archiving fell behind" notification fires |+| Archive slower than source | the unarchived WAL grew by at least the backlog threshold over the last 10 minutes | - |+| Slot keeps extra WAL | the slot's status has been `unreserved` for longer than 5 minutes, or `extended` for longer than 5 minutes while the slot lag grows | - |+| Slot limit approaching | the source sets a limit, and the remaining WAL allowance would run out in under 1 hour if the slot lag keeps growing at its rate of the last 10 minutes | - |+| Near slot rebuild | the slot lag is at least 80% of the configured lag at which Databasus rebuilds the slot, and the slot's status is neither `extended` nor `unreserved` | - |+| Local queue filling | the local queue is at least half the size at which the receiver is paused | - |+| Frequent restarts | receiver restarts and streaming session starts in the last hour add up to 3 or more | - |+| Forced WAL switch refused | the newest sample says the source refused the forced WAL switch | - |++The backlog threshold is 64 MiB or four WAL segments, whichever is larger. Growth of the unarchived WAL SHALL be measured between the lowest value in the first 2.5 minutes of the window and the lowest value in its last 2.5 minutes, so normal upload batches do not count as growth.++When the newest sample is more than 2 minutes old, reasons read from that sample SHALL be dropped, except the source unreachable reason described in the table. The WAL chain broken reason does not depend on samples and stays.++Reasons read from the slot or the archive progress point SHALL be dropped while the newest sample has no source-side values.++The statistics SHALL also list notices, which never change the verdict:++- **no slot WAL limit**: the newest sample was taken with the source reachable, the slot's status is not `lost`, and the source sets no limit on WAL kept for the slot;+- **slot keeps extra WAL steadily**: the slot's status has been `extended` for longer than 5 minutes while the slot lag does not grow;+- **no full backup yet**: no full backup of the database has completed, so archived WAL cannot be restored yet.++#### Scenario: Everything in order++- **WHEN** the source is reachable, archiving keeps pace and no threshold above is crossed+- **THEN** the verdict is healthy and no reason is listed++#### Scenario: Single unusual sample++- **WHEN** only the newest sample shows the local queue above half its pause size+- **THEN** the local queue filling reason is not listed++#### Scenario: Short network blip++- **WHEN** the source stopped answering 30 seconds ago+- **THEN** the source unreachable reason is not listed++#### Scenario: Source unreachable for a few minutes++- **WHEN** the source has been unreachable for 3 minutes and the streamer keeps sampling+- **THEN** the verdict is needs attention with the source unreachable reason and the time it began++#### Scenario: Source down for a while++- **WHEN** the newest sample found the source unreachable, the streamer then stopped, and the source has been unreachable for 6 minutes+- **THEN** the verdict is broken with the source unreachable reason, not the streaming stopped reason++#### Scenario: Archive stuck++- **WHEN** the source keeps writing and the archive progress point has not moved for 12 minutes+- **THEN** the verdict is needs attention with the archive not advancing reason+- **AND** after 30 minutes without movement the same reason is listed at the broken level++#### Scenario: Streamer stopped++- **WHEN** the streamer failed and the newest sample, taken with the source reachable, is ten minutes old+- **THEN** the verdict is broken with the streaming stopped reason+- **AND** the response carries the time of that newest sample+- **AND** no other reason read from that sample is listed++#### Scenario: Restart after a deploy++- **WHEN** Databasus restarted 20 seconds ago after 10 minutes of downtime, and the new session has not taken a sample yet+- **THEN** the verdict is collecting data, not broken++#### Scenario: Crash loop on a new database++- **WHEN** WAL streaming was enabled five minutes ago and every session has failed before its first sample+- **THEN** the verdict is broken with the streaming stopped reason++#### Scenario: Slot rebuilt++- **WHEN** Databasus rebuilt the slot after it was lost and the requested full backup has not completed yet+- **THEN** the verdict is broken with the WAL chain broken reason, even though the new slot is healthy+- **AND** once a newer full backup completes, the reason is no longer listed++#### Scenario: Gap bridged by an incremental backup++- **WHEN** the newest chain has a WAL gap below the archive progress point, an incremental backup of that chain completed after the gap, and every segment after that backup is archived without a gap+- **THEN** the WAL chain broken reason is not listed+- **AND** the latest restorable moment is the time Databasus received the newest archived segment++#### Scenario: Gap after the newest incremental backup++- **WHEN** an incremental backup of the newest chain completed, and a WAL gap below the archive progress point follows it+- **THEN** the verdict is broken with the WAL chain broken reason++#### Scenario: Failed incremental backup after the gap++- **WHEN** the only incremental backup started after the gap failed or is still running+- **THEN** the verdict is broken with the WAL chain broken reason++#### Scenario: Slot removed on the source++- **WHEN** the newest sample found the source without the slot+- **THEN** the verdict is broken with the slot missing reason, not the source unreachable reason++#### Scenario: Just enabled++- **WHEN** WAL streaming was just enabled and no sample exists yet+- **THEN** the verdict is collecting data++#### Scenario: Backups disabled++- **WHEN** a database in WAL streaming mode has its backups disabled+- **THEN** the verdict is not streaming+- **AND** the series still holds the samples recorded before++#### Scenario: Several problems at once++- **WHEN** the local queue has been half full for two samples and the slot is missing+- **THEN** the verdict is broken+- **AND** both reasons are listed, each with its own level++#### Scenario: Busy cluster with steady extra WAL++- **WHEN** the slot's status has been `extended` for an hour while the slot lag stays flat+- **THEN** the slot keeps extra WAL reason is not listed+- **AND** the slot keeps extra WAL steadily notice is listed++#### Scenario: Paused receiver above the rebuild lag++- **WHEN** the receiver is paused for a full local queue and the slot lag is at 90% of the rebuild lag with status `reserved`+- **THEN** the near slot rebuild reason is listed++#### Scenario: No limit on the source++- **WHEN** the source's `max_slot_wal_keep_size` is `-1` and nothing else is wrong+- **THEN** the verdict is healthy+- **AND** the no slot WAL limit notice is listed++#### Scenario: Slot already lost++- **WHEN** the newest sample reports the slot's status as `lost`+- **THEN** the no slot WAL limit notice is not listed++### Requirement: The statistics API is a documented, unit-explicit contract++The statistics SHALL be served by an authenticated API endpoint documented with the rest of the API. Every amount SHALL carry its unit in its name, in bytes, bytes per second, seconds or milliseconds. Every time SHALL be an absolute UTC time. Every verdict, state, reason and notice SHALL be a stable code from a documented list, not display text, so other consumers can rely on it.++A response SHALL hold:++- the health verdict, its reasons and its notices;+- whether a full backup is requested or running;+- the latest restorable moment, or that none exists yet;+- the restorable stretches of the newest chain, each with its start and end;+- the streamer's state;+- the current values from the newest sample, the time of that sample and the time the newest WAL segment was archived;+- the keeping-up summary;+- a chart series for the requested period.++A request for a database that is not a PostgreSQL physical database SHALL be refused as invalid. A PostgreSQL physical database outside WAL streaming mode SHALL get the not streaming verdict and whatever samples it still has.++#### Scenario: Codes, not text++- **WHEN** a client reads a response for a database that needs attention+- **THEN** the verdict, each reason and each notice are codes from the documented lists+- **AND** no field holds a sentence meant for display++#### Scenario: Logical database++- **WHEN** a user requests statistics for a logical database they can view+- **THEN** the request is refused as invalid++#### Scenario: Switched out of WAL streaming++- **WHEN** a physical database switched from WAL streaming to full and incremental mode yesterday+- **THEN** the verdict is not streaming+- **AND** the series holds the samples recorded before the switch++#### Scenario: Restorable moment as UTC time++- **WHEN** a client reads a response for a database with a completed full backup+- **THEN** the latest restorable moment is an absolute UTC time+- **AND** each restorable stretch starts and ends at an absolute UTC time++### Requirement: The Monitoring tab speaks plain language++Every label, headline, sentence, legend and chart title the tab shows by default SHALL avoid the terms "WAL", "slot", "LSN" and "lag". The tab SHALL call the unarchived WAL "not saved to storage yet" and the slot lag "not received by Databasus yet", and SHALL say that the second is part of the first. Technical names SHALL appear only in explanations shown on hover or keyboard focus, in the technical details section, and in a "what to do" sentence that names a setting or permission to change, such as `max_slot_wal_keep_size`.++Each reason and each notice SHALL have one sentence about what happened, with its amounts and, where known, how long it has lasted, and one sentence about what to do. When Databasus resolves a condition by itself, the second sentence SHALL say so, and only then. For a broken chain or a missing slot, the second sentence SHALL ask the user to start a full backup unless one is requested or running. Where the banner offers the full backup button, the button takes the place of that sentence. Durations SHALL be rounded for reading: minutes under an hour, hours and minutes under a day, days and hours beyond.++#### Scenario: Plain names++- **WHEN** a user opens the Monitoring tab of a healthy database+- **THEN** no default label, legend or chart title contains "WAL", "slot", "LSN" or "lag"++#### Scenario: Broken chain without a pending full backup++- **WHEN** the WAL chain broken reason is shown and no full backup is requested or running+- **THEN** the tab asks the user to start a full backup, through the button or, for a user who cannot manage the database, through the sentence about what to do+- **AND** does not say that Databasus handles it by itself++#### Scenario: Every reason has an action++- **WHEN** any reason or notice is shown+- **THEN** it has both a sentence about what happened and a sentence about what to do++### Requirement: The Monitoring tab leads with the verdict++The tab SHALL open with a verdict banner. Its headline SHALL be:++- for the healthy verdict: all changes are being saved;+- for the needs attention and broken verdicts: the title of the most severe reason, broken reasons before needs-attention ones and, within one level, in the order the statistics list them;+- for the collecting data and not streaming verdicts, and while the current state cannot be confirmed: what they are today.++The banner SHALL use the verdict's color, green, orange, red or neutral gray, together with an icon and words, so color is never the only signal. Screen readers SHALL announce a change of the headline.++Under the headline, the banner SHALL show the headline reason's sentence about what happened and its sentence about what to do, then the restore sentence. While the banner offers the full backup button, it SHALL leave out the headline reason's sentence about what to do, because the button is that action. The headline reason's sentence about what happened SHALL not repeat the headline. The time of the newest measurement SHALL sit in the headline row. Every other reason SHALL follow inside the same banner as a compact line with its level icon, its title and both its sentences, broken ones first. The banner SHALL not show the keeping-up sentence. The not streaming banner SHALL say how to turn streaming on and link to the database's configuration.++#### Scenario: Healthy database++- **WHEN** the verdict is healthy+- **THEN** the headline is green and says that all changes are being saved+- **AND** no reason is shown++#### Scenario: Problem named in the headline++- **WHEN** the verdict is broken because the WAL chain is broken+- **THEN** the headline is red and says that changes were lost between backups+- **AND** the banner does not say that the database writes almost nothing++#### Scenario: Problems listed++- **WHEN** the verdict is broken because the slot is missing and the local queue is filling+- **THEN** the headline is red and names the slot missing reason+- **AND** the local queue reason follows inside the banner as a compact line++### Requirement: The Monitoring tab explains whether archiving keeps up++Under the figures, the tab SHALL describe the keeping-up state in one or two plain sentences:++- keeping up: Databasus saves changes as fast as the database writes them, with both rates;+- falling behind: the database writes changes faster than Databasus saves them, by how much per second, how much is not saved yet and how fast that amount grows;+- catching up: Databasus is saving a backlog, how much is left and about how long it takes;+- idle: the database writes almost nothing, and new changes reach storage within minutes;+- unknown: no sentence, because the figures already say not measured.++When an estimate until the rebuild lag or until the WAL allowance runs out exists and is under one day, the tab SHALL add what happens then: Databasus will start a new backup chain from a full backup, or the source will drop changes that Databasus has not received yet.++#### Scenario: Falling behind explained++- **WHEN** the source writes 21 MB/s, Databasus archives 12 MB/s and 3.4 GB is unarchived+- **THEN** the tab says that the database writes changes faster than Databasus saves them, by about 9 MB/s+- **AND** says that 3.4 GB is not saved yet and grows by about 32 GB an hour++#### Scenario: Consequence only when near++- **WHEN** the estimate until the rebuild lag is three days+- **THEN** the tab adds no sentence about a new backup chain++#### Scenario: Unknown state++- **WHEN** the keeping-up state is unknown+- **THEN** the tab shows no keeping-up sentence++### Requirement: The Monitoring tab shows where unsaved changes are++The technical details section SHALL show the path of changes as three stages, source, Databasus and storage, with:++- at the source: what is not received by Databasus yet, against the rebuild lag and, when the source sets a limit, the remaining allowance;+- in Databasus: the local queue, against the size at which the receiver is paused, and whether receiving is paused;+- in storage: how long ago the newest WAL segment was archived;+- between the stages: the source's write rate and the archive rate, on a connector that points to the next stage.++The stages SHALL sit in one frame as nodes of a single line, each with an icon and its name, and each rate SHALL sit on the line between two nodes, like the throughput of a pipe, with its name and the color of its chart line under it. Under the nodes the section SHALL say that the rates are averages over the last 10 minutes and the amounts are current.++Each stage SHALL show its amount under a short label. An empty amount SHALL read as nothing waiting, with a success icon, instead of 0 B over an empty meter. An amount above zero SHALL show as a number and, when it has a limit, say how much of the limit it is, such as "300 MB of 512 MB", next to a thin meter; the limit's sentence, such as the size at which receiving pauses, SHALL appear only then and otherwise stay in the explanation on hover or keyboard focus. An amount above its limit SHALL show as over the limit, not as a full bar. A stage without a problem SHALL stay neutral; a stage with a problem SHALL take the color of the most severe reason about that stage on its icon, together with an icon and the word for that level, so color is never the only signal. The WAL chain broken reason concerns the backup history rather than a stage, so it SHALL color no stage. Each amount on a stage SHALL offer a short explanation on hover or keyboard focus. When the section is wide enough the stages SHALL sit in a row joined by arrows pointing right; otherwise they SHALL stack vertically joined by arrows pointing down. Only one arrow direction SHALL be visible at a time.++#### Scenario: Backlog in the local queue++- **WHEN** the slot lag is small and the local queue holds 300 MB of its 512 MB pause size for two samples+- **THEN** the Databasus stage shows 300 MB of 512 MB in the needs-attention color with its icon and word+- **AND** the source stage stays neutral++#### Scenario: Database writing in bursts++- **WHEN** the database writes a burst every three minutes, each burst reaches storage within seconds, and the average write rate over 10 minutes is 54.6 KB/s+- **THEN** the source and Databasus stages say that nothing is waiting+- **AND** the links show 54.6 KB/s+- **AND** the section says that the rates are averages over the last 10 minutes and the amounts are current++#### Scenario: Broken chain with healthy stages++- **WHEN** the only reason is the WAL chain broken reason and the newest segment was archived seconds ago+- **THEN** every stage stays neutral, without a problem icon++#### Scenario: Wide screen++- **WHEN** the path of changes has room for its stages in a row+- **THEN** each link between stages shows one arrow pointing right and no arrow pointing down++#### Scenario: Narrow screen++- **WHEN** the path of changes has no room for its stages in a row+- **THEN** the stages stack vertically+- **AND** each link between stages shows one arrow pointing down and no arrow pointing right++### Requirement: The Monitoring tab shows charts for the selected period++The tab SHALL offer the last hour, day and week, and show one chart for the selected period below the figures: the source write rate and the archive rate. The technical details section SHALL show, for the same period:++- what is not saved to storage yet and what is not received by Databasus yet on one chart;+- the local queue size with its pause size, and receiver restarts and pauses.++Axes SHALL show formatted amounts and local times. The amount axis SHALL mark round amounts in the unit it shows, such as 256 KB, 512 KB and 768 KB, not fractions of another unit. Each chart SHALL show its title, its legend and, for the main chart, the period switch in one header above the plot. The plot SHALL keep a fixed height, because the tab itself has a maximum width. Hovering a time on one chart SHALL mark the same time on the others and show the formatted values. When the source write rate and the archive rate are equal, both lines SHALL stay distinguishable.++Intervals without samples SHALL show as gaps. A run of two or more intervals without samples after the data starts SHALL be shaded on the chart, and the tab SHALL say from when to when there are no measurements.++A chart SHALL appear only when the series holds at least four points with values. Otherwise the tab SHALL say that there is not enough data for this period yet and that a shorter period may already have a chart. When the data starts inside the period, the time axis SHALL start at the first point with values and the tab SHALL say since when it has data. The amount axis SHALL reach at least 64 KiB/s on the rate chart and at least one WAL segment on the amount charts, so small values stay near the bottom instead of filling the chart.++The technical details section SHALL also show the raw values with their technical names: the slot's status, the remaining allowance, the average and longest segment write, the upload concurrency, the ratio of WAL to stored bytes, the WAL segment size and the streaming session's start.++#### Scenario: Archiving falls behind on the chart++- **WHEN** every point of the hour holds a source write rate of 21 MB/s and an archive rate of 12 MB/s, and a rising unarchived amount+- **THEN** the archive series lies below the source series at every point+- **AND** the not-saved-yet series in the technical details rises across the hour++#### Scenario: No history yet++- **WHEN** the verdict is collecting data and the series holds no point with values+- **THEN** the tab shows the explanation instead of the chart++#### Scenario: Two minutes of data++- **WHEN** streaming started two minutes ago and the hour series holds two points with values+- **THEN** the tab shows the explanation instead of the chart++#### Scenario: Data started inside the period++- **WHEN** the hour series holds values only for its last 20 minutes+- **THEN** the chart's time axis starts 20 minutes ago+- **AND** the tab says since when it has data++#### Scenario: Measurements missing for five minutes++- **WHEN** the hour series has values except for five consecutive one-minute points in its middle+- **THEN** the chart shades those five minutes+- **AND** the tab says that there are no measurements from the first to the last of them++#### Scenario: Round rate ticks++- **WHEN** the rate axis reaches 1 MiB/s+- **THEN** its ticks read 0 B/s, 256 KB/s, 512 KB/s, 768 KB/s and 1 MB/s++#### Scenario: Equal rates++- **WHEN** the database writes and Databasus saves at the same rate at every point+- **THEN** both lines are visible on the chart++#### Scenario: Quiet database++- **WHEN** every point of the hour holds a source write rate of 2 KB/s+- **THEN** the rate axis reaches at least 64 KB/s and the line stays near its bottom++### Requirement: The Monitoring tab stays current without disturbing the reader++The tab SHALL read the current values every second, and the full statistics every 30 seconds, in every period while it is open and the browser tab is visible. It SHALL refresh both at once when the browser tab becomes visible again, and the statistics when the period changes. The figures, the restore timeline's end, the path of changes and the time of the newest measurement SHALL use the current values while they are newer than the newest sample. While the latest restorable moment of the statistics equals their newest save, the banner's restorable moment and the end of the newest restorable stretch SHALL follow the newest save of the current values, so the banner never names an older moment than the figure next to it; the verdict, the keeping-up summary, the rates and the charts SHALL use the statistics.++The tab SHALL show the age of the newest measurement, updated every second, and mark it as live only while that measurement is younger than 2 minutes. When the last successful refresh of the statistics is older than 2 minutes, the headline SHALL turn neutral gray and say that the current state cannot be confirmed, with the last known verdict and its age. A failed reading of the current values SHALL leave the values of the statistics on screen without an error of its own.++A refresh SHALL keep the previous content on screen until the new content arrives, keep the scroll position and the selected period, and not replay the charts' entry animation. Changed numbers and the headline color SHALL change with a short transition. When the reader's system asks for reduced motion, there SHALL be no transitions, no pulsing and no chart animation. A failed refresh of the statistics SHALL keep the last content, say that refreshing failed, and keep retrying on the same schedule. A failed first load SHALL show the error and a retry button.++#### Scenario: Status changes while open++- **WHEN** the tab is open on the day view and the verdict changes from healthy to needs attention+- **THEN** the headline changes within 30 seconds without reloading the page++#### Scenario: Buffer drains while open++- **WHEN** the local queue drains while the tab is open+- **THEN** the path of changes shows the new amount within about a second++#### Scenario: Segment saved between two statistics refreshes++- **WHEN** the latest restorable moment equals the newest save and a new segment reaches storage 5 seconds after the statistics refresh+- **THEN** within about a second the banner names the new save's time as the moment the database can be restored to++#### Scenario: Browser tab hidden++- **WHEN** the browser tab is hidden for ten minutes and then shown again+- **THEN** no refresh happened while it was hidden+- **AND** a refresh happens as soon as it is shown++#### Scenario: Refresh keeps failing++- **WHEN** refreshes have failed for 3 minutes after a healthy response+- **THEN** the headline is gray and says the state cannot be confirmed, last known healthy 3 minutes ago+diff --git a/openspec/changes/archive/2026-10-21-rethink-wal-monitoring-tab/tasks.md b/openspec/changes/archive/2026-10-21-rethink-wal-monitoring-tab/tasks.mdnew file mode 100644index 00000000..9f752928--- /dev/null+++ b/openspec/changes/archive/2026-10-21-rethink-wal-monitoring-tab/tasks.md@@ -0,0 +1,56 @@+## 1. Latest restorable moment in the API++- [x] 1.1 Split `ResolveRestoreSet` in `core/physical/chain_view/restore_set.go` into a private latest-reach resolution and the existing target checks, and add `ChainViewService.GetLatestRestorableAt` returning the reachable time or nil without a chain (design D1). Verify with `just test-package ./internal/features/backups/backups/core/physical/chain_view/...` in `backend/`.+- [x] 1.2 Add `latestRestorableAt` to `GetWalStreamStatisticsResponse` and fill it in `services/physical_wal_stream_statistics.go`, with controller tests for no gaps, a gap in the newest chain, an incremental backup completed after the gap, a full backup without WAL and no full backup. Verify with `just test-package ./internal/features/backups/backups/controllers/physical/...` in `backend/`.+- [x] 1.3 Describe the field in the endpoint's Swagger annotation and regenerate the docs with `swag init -d . -g cmd/main.go -o swagger` in `backend/`. Verify that `grep -c latestRestorableAt backend/swagger/swagger.yaml` is above zero and that `just lint` in `backend/` passes.++## 2. Frontend rules and strings++- [x] 2.1 Add `latestRestorableAt` to the `WalStreamStatistics` model in `entity/backups/physical/model`, and add the new keys of design D8 to all six interface dictionaries. Verify with `pnpm --dir frontend typecheck` and `pnpm --dir frontend test src/shared/i18n`.+- [x] 2.2 Map `WAL_CHAIN_BROKEN` to no stage in `REASON_STAGES` and skip it in `getStageTones` (design D7), with a test that a broken chain alone leaves every stage healthy. Verify with `pnpm --dir frontend test src/features/backups/physical/monitoring/lib/pathStages.test.ts`.+- [x] 2.3 Add the pure full backup action function of design D3, with tests for available on a broken chain, available on a missing slot, available on a healthy verdict without a completed full backup, hidden without manage permission, hidden without a reason, hidden for not streaming, hidden for collecting data, hidden while unconfirmed, hidden while a full backup is pending, requesting while the flag is set, and available again once the flag clears after a failed request. Verify with `pnpm --dir frontend test src/features/backups/physical/monitoring/lib`.+- [x] 2.4 Extend `getVerdictBanner` to compose the headline, the headline reason, the other reasons and the restore sentence (design D2), with tests for the healthy headline, a reason title as headline, broken reasons before needs-attention ones, all four restore sentence cases, a broken chain whose moment already reaches the newest archived segment getting the plain sentence, the restore sentence during collecting data without a full backup, a moment from today and from an earlier day, and the unconfirmed state keeping the last known moment. Verify with `pnpm --dir frontend test src/features/backups/physical/monitoring/lib/verdictBanner.test.ts`.+- [x] 2.5 Add `hasEnoughChartPoints`, `getChartTimeDomain` and `getAmountAxisMaximum` to `chartRows.ts` and remove `hasAnyChartValues` (design D6), with tests for three and four points, data starting inside the period, data covering the whole period and the minimum top. Verify with `pnpm --dir frontend test src/features/backups/physical/monitoring/lib/chartRows.test.ts`.+- [x] 2.6 Add `getMonitoringFigures` (design D4), with tests for the busy healthy case (15 seconds ago, 20 MB, 10 MB/s against 10 MB/s), null rates when no sample in the window holds a write value, and null for the collecting data and not streaming verdicts. Verify with `pnpm --dir frontend test src/features/backups/physical/monitoring/lib/monitoringFigures.test.ts`.++## 3. Frontend layout++- [x] 3.1 Rebuild `VerdictBannerComponent` around the composed banner: headline, headline reason, compact other reasons, restore sentence and the full backup button wired to `physicalBackupsApi.triggerPhysicalBackup(database.id, 'full')`, with `WalStreamRefreshController.retry()` after success and errors through `translateApiError`. Pass `isCanManageDBs` from `DatabaseComponent` to the tab, and delete `MonitoringReasonsComponent`. Verify with `pnpm --dir frontend typecheck` and `pnpm --dir frontend test src/features/backups/physical/monitoring`.+- [x] 3.2 Add the figures row from `getMonitoringFigures`, rendering unknown values as "not measured", with the keeping-up sentence and its consequences as its caption (design D4), and drop the unknown sentence from `getKeepingUpSentences`. Verify with `pnpm --dir frontend test src/features/backups/physical/monitoring/lib/monitoringFigures.test.ts src/features/backups/physical/monitoring/lib/keepingUpSentences.test.ts` and `pnpm --dir frontend typecheck`.+- [x] 3.3 Show one main chart with the new time domain, amount axis minimum and empty state, and add the collapsed tips and technical details sections holding the notices, the path of changes, the two secondary charts and the raw values (design D5, D6). Put the arrow classes on wrapper elements (design D7). Verify with `pnpm --dir frontend typecheck` and `pnpm --dir frontend lint`.+- [x] 3.4 Update `WalStreamMonitoringSections.test.tsx` for the healthy banner, the broken chain banner with its restore sentence and button, no button for a read-only user, the figures row with "not measured", the collapsed tips header with its count, the technical details body showing the path of changes, both secondary charts' titles and the raw values, the "not enough data" and "data since" chart captions, and each arrow icon inside a wrapper carrying its breakpoint class. Verify with `pnpm --dir frontend test src/features/backups/physical/monitoring/ui`.+- [x] 3.5 Remove the dictionary keys and helpers only the deleted blocks used from all six dictionaries and the slice, then run the frontend checks. Verify with `pnpm --dir frontend lint`, `pnpm --dir frontend typecheck`, `pnpm --dir frontend test` and `pnpm --dir frontend build`.++## 4. Restore coverage and the broken chain verdict++- [x] 4.1 Add `ChainViewService.GetRestoreCoverage` with the latest restorable moment, the merged restorable ranges and the gaps the latest restore cannot cross, and remove `GetLatestRestorableAt` (design D1). Cover it with `chain_view` tests for no full backup, contiguous WAL, a gap without an incremental, a gap bridged by a completed incremental, an incremental before the gap, a failed, chain-broken or running incremental after the gap, two gaps with only the first bridged, an incremental stopping inside a missing segment, a segment still uploading and a newer full backup, each checking that the last range ends at the latest restorable moment. Verify with `just test-package ./internal/features/backups/backups/core/physical/chain_view/...` in `backend/`.+- [x] 4.2 Write the controller test for a bridged gap with a streamer and samples, and see it fail with `WAL_CHAIN_BROKEN` on the current code. Then pass the blocking gaps to the verdict, rename `NewestChainGaps` to `RestoreBlockingGaps`, and add `restorableRanges` to the response and its Swagger description. Add controller tests for a gap after the newest incremental, a failed incremental after the gap and no full backup, and cover `restorableRanges` in the response format check. Verify with `just test-package ./internal/features/backups/backups/controllers/physical/... ./internal/features/backups/backups/core/physical/wal_health/...` and `just lint` in `backend/`.++## 5. Restore timeline, figure cards, chart and banner++- [x] 5.1 Add `restorableRanges` to the `WalStreamStatistics` model and the test fixture, add `getRestoreTimeline` with tests for one range, a gap between two ranges, the minimum width of a short gap and the not saved yet tail, and render `RestoreTimelineComponent` between the figures and the main chart (design D10). Simplify `isRestoreLimitedByBrokenChain` to the reason alone (design D2). Verify with `pnpm --dir frontend test src/features/backups/physical/monitoring/lib`.+- [x] 5.2 Turn the figures into four cards with the chart's rate labels and colors, and remove `figures.speed` and `figures.speedValue` (design D4). Verify with `pnpm --dir frontend typecheck`.+- [x] 5.3 Add `getBinaryAxisTicks` and `getMissingDataRanges` with tests, replace `getAmountAxisMaximum`, and rebuild the chart header, legend, height, saved-to-storage band and missing data shading and caption (design D6). Verify with `pnpm --dir frontend test src/features/backups/physical/monitoring/lib/chartRows.test.ts`.+- [x] 5.4 Limit the banner's text width, move the measured label into the headline row, leave out the headline reason's "what to do" sentence while the full backup button shows, and rewrite the broken chain's "what happened" sentence in all six dictionaries (design D2, D11). Return null from the duration helpers for non-finite input and use the restore sentence without an age then, with tests (design D12). Verify with `pnpm --dir frontend test src/features/backups/physical/monitoring src/shared/i18n`.+- [x] 5.5 Update `WalStreamMonitoringSections.test.tsx` for the four figure cards, the timeline's lost-stretch sentence, and the "what to do" sentence hidden next to the button and shown without it. Run the frontend checks, and check the tab in a browser at 1240, 1440 and 2560 px. Verify with `pnpm --dir frontend lint`, `pnpm --dir frontend typecheck`, `pnpm --dir frontend test` and `pnpm --dir frontend build`.++## 6. Current values every second and the pipeline++- [x] 6.1 Remember the newest slot probe in `WalStreamSupervisor`, add `GetLiveState`, keep each running supervisor on `runningStreamer` with `PhysicalWalStreamSupervisor.GetLiveState(databaseID)`, and add `GET /backups/physical/database/:id/wal-stream/live` with its Swagger description (design D13). Cover it with controller tests for a viewer reading a streamer's values, a database without a running streamer, a user without access and a logical database. Verify with `just test-package ./internal/features/backups/backups/controllers/physical/... ./internal/features/backups/backups/backuping/physical/...`, `just test-package -run Test_GetLiveState ./internal/features/backups/backups/usecases/physical/postgresql/` and `just lint` in `backend/`.+- [x] 6.2 Add `WalStreamLiveController` reading the current values every second while visible, with tests for the schedule, a hidden tab, a failed reading and stop, and overlay newer live values onto the statistics for the figures, the restore timeline and the path of changes (design D13). Verify with `pnpm --dir frontend test src/features/backups/physical/monitoring/lib`.+- [x] 6.3 Rebuild `ChangesPathComponent` as the pipeline of design D14, return neutral from `getStageTones` for a stage without a reason, and update its static-markup test. Verify with `pnpm --dir frontend lint`, `pnpm --dir frontend typecheck`, `pnpm --dir frontend test` and `pnpm --dir frontend build`, and check it in a browser at 1240, 1440 and 2560 px.++## 7. Width, open sections and a consistent restore moment++- [x] 7.1 Write the `Test_GetLiveState` case for an archive progress point past the probed position and see it fail with an unknown amount, then report zero (design D13). Verify with `just test-package ./internal/features/backups/backups/usecases/physical/postgresql/ -run Test_GetLiveState` and `just lint` in `backend/`.+- [x] 7.2 Move the restore point and the end of the newest restorable range with the live save while the statistics' restore point equals their newest save, and name the newest restorable stretch's start in the restore sentence when an earlier stretch cannot be restored, with tests and the two new keys in all six dictionaries (design D2, D13). Verify with `pnpm --dir frontend test src/features/backups/physical/monitoring/lib src/shared/i18n`.+- [x] 7.3 Cap the tab at `max-w-6xl`, use fixed chart heights, a 64 KiB/s rate axis minimum and `text-xl` values, lay out the path of changes by a container query, and show the technical details and the tips without a `Collapse`, removing the tips title from all six dictionaries (design D5, D6, D11). Update the static-markup tests and check the tab in a browser at 1240, 1440 and 2560 px. Verify with `pnpm --dir frontend lint`, `pnpm --dir frontend typecheck`, `pnpm --dir frontend test` and `pnpm --dir frontend build`.+- [x] 7.4 Rebuild `ChangesPathComponent` as the flow strip of design D14: one frame, a subgrid row of icons, titles and lines with the rates on the lines, "nothing waiting" for an empty queue, limit sentences only above zero, and the averages caption; mark the two rate cards as 10-minute averages; add `path.nothingWaiting`, `path.ratesCaption` and `figures.averageHint` and remove `path.noAllowanceLimit` in all six dictionaries. Update the static-markup tests and check the strip in a browser at 900, 1240 and 1440 px. Verify with `pnpm --dir frontend lint`, `pnpm --dir frontend typecheck`, `pnpm --dir frontend test` and `pnpm --dir frontend build`.++## Change verification++```sh+just test-package ./internal/features/backups/backups/core/physical/chain_view/... ./internal/features/backups/backups/core/physical/wal_health/... ./internal/features/backups/backups/controllers/physical/...+just test-package ./internal/features/backups/backups/usecases/physical/postgresql/...+pnpm --dir frontend test src/features/backups/physical/monitoring src/shared/i18n+```diff --git a/openspec/specs/physical-backups/wal-stream-monitoring/spec.md b/openspec/specs/physical-backups/wal-stream-monitoring/spec.mdindex 00253a57..dfca12a8 100644--- a/openspec/specs/physical-backups/wal-stream-monitoring/spec.md+++ b/openspec/specs/physical-backups/wal-stream-monitoring/spec.md@@ -160,6 +160,8 @@ A response SHALL hold:- the health verdict, its reasons and its notices;- whether a full backup is requested or running;+- the latest restorable moment, or that none exists yet;+- the restorable stretches of the newest chain, each with its start and end;- the streamer's state;- the current values from the newest sample, the time of that sample and the time the newest WAL segment was archived;- the keeping-up summary;@@ -184,6 +186,12 @@ A request for a database that is not a PostgreSQL physical database SHALL be ref- **THEN** the verdict is not streaming- **AND** the series holds the samples recorded before the switch+#### Scenario: Restorable moment as UTC time++- **WHEN** a client reads a response for a database with a completed full backup+- **THEN** the latest restorable moment is an absolute UTC time+- **AND** each restorable stretch starts and ends at an absolute UTC time+### Requirement: The streamer's state accounts for its heartbeat and repeated failuresThe streamer's state SHALL be running only while Databasus marks it running and its heartbeat is younger than the age after which another tick may take the streamer over. It SHALL be not running when it is marked failed or its heartbeat is older. It SHALL be not started when no streamer has ever run for the database.@@ -223,7 +231,7 @@ Each reason SHALL carry its code and its level. It SHALL also carry the time the|---|---|---|| Streaming stopped | - | the streamer has been failing for 1 minute or longer, or the newest sample is older than 2 minutes, and the newest sample did not find the source unreachable || Source unreachable | the newest sample found the source unreachable, and the source has been unreachable for 1 to 5 minutes since | the same for 5 minutes or longer, also when streaming stopped after that sample |-| WAL chain broken | - | the newest completed full backup's chain has a WAL gap below the archive progress point; it clears when a newer full backup completes |+| WAL chain broken | - | the newest completed full backup's chain has a WAL gap below the archive progress point that the latest restore cannot cross, because no completed backup of that chain starts after the gap; it clears when a completed incremental backup of that chain or a newer full backup starts after the gap || Slot missing | - | the newest sample found the source without the slot || Slot lost | - | the newest sample reports the slot's status as `lost` || Archive not advancing | the archive progress point has stood still for 10 minutes or longer while the source keeps writing | the same for the archive staleness threshold of 30 minutes or longer, which is when the "archiving fell behind" notification fires |@@ -301,6 +309,22 @@ The statistics SHALL also list notices, which never change the verdict:- **THEN** the verdict is broken with the WAL chain broken reason, even though the new slot is healthy- **AND** once a newer full backup completes, the reason is no longer listed+#### Scenario: Gap bridged by an incremental backup++- **WHEN** the newest chain has a WAL gap below the archive progress point, an incremental backup of that chain completed after the gap, and every segment after that backup is archived without a gap+- **THEN** the WAL chain broken reason is not listed+- **AND** the latest restorable moment is the time Databasus received the newest archived segment++#### Scenario: Gap after the newest incremental backup++- **WHEN** an incremental backup of the newest chain completed, and a WAL gap below the archive progress point follows it+- **THEN** the verdict is broken with the WAL chain broken reason++#### Scenario: Failed incremental backup after the gap++- **WHEN** the only incremental backup started after the gap failed or is still running+- **THEN** the verdict is broken with the WAL chain broken reason+#### Scenario: Slot removed on the source- **WHEN** the newest sample found the source without the slot@@ -442,9 +466,9 @@ The database page SHALL show a Monitoring tab for a PostgreSQL physical database### Requirement: The Monitoring tab speaks plain language-Every label, headline, sentence, legend and chart title the tab shows by default SHALL avoid the terms "WAL", "slot", "LSN" and "lag". The tab SHALL call the unarchived WAL "not saved to storage yet" and the slot lag "not received by Databasus yet", and SHALL say that the second is part of the first. Technical names SHALL appear only in explanations shown on hover or keyboard focus, in the details section, and in a "what to do" sentence that names a setting or permission to change, such as `max_slot_wal_keep_size`.+Every label, headline, sentence, legend and chart title the tab shows by default SHALL avoid the terms "WAL", "slot", "LSN" and "lag". The tab SHALL call the unarchived WAL "not saved to storage yet" and the slot lag "not received by Databasus yet", and SHALL say that the second is part of the first. Technical names SHALL appear only in explanations shown on hover or keyboard focus, in the technical details section, and in a "what to do" sentence that names a setting or permission to change, such as `max_slot_wal_keep_size`.-Each reason and each notice SHALL have one sentence about what happened, with its amounts and, where known, how long it has lasted, and one sentence about what to do. When Databasus resolves a condition by itself, the second sentence SHALL say so, and only then. For a broken chain or a missing slot, the second sentence SHALL ask the user to start a full backup unless one is requested or running. Durations SHALL be rounded for reading: minutes under an hour, hours and minutes under a day, days and hours beyond.+Each reason and each notice SHALL have one sentence about what happened, with its amounts and, where known, how long it has lasted, and one sentence about what to do. When Databasus resolves a condition by itself, the second sentence SHALL say so, and only then. For a broken chain or a missing slot, the second sentence SHALL ask the user to start a full backup unless one is requested or running. Where the banner offers the full backup button, the button takes the place of that sentence. Durations SHALL be rounded for reading: minutes under an hour, hours and minutes under a day, days and hours beyond.#### Scenario: Plain names@@ -454,7 +478,7 @@ Each reason and each notice SHALL have one sentence about what happened, with it#### Scenario: Broken chain without a pending full backup- **WHEN** the WAL chain broken reason is shown and no full backup is requested or running-- **THEN** the tab asks the user to start a full backup+- **THEN** the tab asks the user to start a full backup, through the button or, for a user who cannot manage the database, through the sentence about what to do- **AND** does not say that Databasus handles it by itself#### Scenario: Every reason has an action@@ -464,31 +488,43 @@ Each reason and each notice SHALL have one sentence about what happened, with it### Requirement: The Monitoring tab leads with the verdict-The tab SHALL open with the verdict as a headline: all is well, something needs attention, something is broken, data is being collected, or streaming is off. The headline SHALL use the verdict's color, green, orange, red or neutral gray, together with an icon and words, so color is never the only signal. Screen readers SHALL announce a change of the headline.+The tab SHALL open with a verdict banner. Its headline SHALL be:++- for the healthy verdict: all changes are being saved;+- for the needs attention and broken verdicts: the title of the most severe reason, broken reasons before needs-attention ones and, within one level, in the order the statistics list them;+- for the collecting data and not streaming verdicts, and while the current state cannot be confirmed: what they are today.-The not streaming headline SHALL say how to turn streaming on and link to the database's configuration. Below the headline, the tab SHALL list the reasons, broken ones first. Notices SHALL appear after the reasons in a neutral informational style, and the no slot WAL limit notice SHALL explain in plain words what the limit protects and what it costs.+The banner SHALL use the verdict's color, green, orange, red or neutral gray, together with an icon and words, so color is never the only signal. Screen readers SHALL announce a change of the headline.++Under the headline, the banner SHALL show the headline reason's sentence about what happened and its sentence about what to do, then the restore sentence. While the banner offers the full backup button, it SHALL leave out the headline reason's sentence about what to do, because the button is that action. The headline reason's sentence about what happened SHALL not repeat the headline. The time of the newest measurement SHALL sit in the headline row. Every other reason SHALL follow inside the same banner as a compact line with its level icon, its title and both its sentences, broken ones first. The banner SHALL not show the keeping-up sentence. The not streaming banner SHALL say how to turn streaming on and link to the database's configuration.#### Scenario: Healthy database- **WHEN** the verdict is healthy-- **THEN** the headline is green and says that everything is in order-- **AND** no reason list is shown+- **THEN** the headline is green and says that all changes are being saved+- **AND** no reason is shown++#### Scenario: Problem named in the headline++- **WHEN** the verdict is broken because the WAL chain is broken+- **THEN** the headline is red and says that changes were lost between backups+- **AND** the banner does not say that the database writes almost nothing#### Scenario: Problems listed- **WHEN** the verdict is broken because the slot is missing and the local queue is filling-- **THEN** the headline is red-- **AND** the slot missing reason is listed before the local queue reason+- **THEN** the headline is red and names the slot missing reason+- **AND** the local queue reason follows inside the banner as a compact line### Requirement: The Monitoring tab explains whether archiving keeps up-Right below the headline, the tab SHALL describe the keeping-up state in one or two plain sentences:+Under the figures, the tab SHALL describe the keeping-up state in one or two plain sentences:- keeping up: Databasus saves changes as fast as the database writes them, with both rates;- falling behind: the database writes changes faster than Databasus saves them, by how much per second, how much is not saved yet and how fast that amount grows;- catching up: Databasus is saving a backlog, how much is left and about how long it takes;- idle: the database writes almost nothing, and new changes reach storage within minutes;-- unknown: no current numbers are available.+- unknown: no sentence, because the figures already say not measured.When an estimate until the rebuild lag or until the WAL allowance runs out exists and is under one day, the tab SHALL add what happens then: Databasus will start a new backup chain from a full backup, or the source will drop changes that Databasus has not received yet.@@ -503,59 +539,134 @@ When an estimate until the rebuild lag or until the WAL allowance runs out exist- **WHEN** the estimate until the rebuild lag is three days- **THEN** the tab adds no sentence about a new backup chain+#### Scenario: Unknown state++- **WHEN** the keeping-up state is unknown+- **THEN** the tab shows no keeping-up sentence+### Requirement: The Monitoring tab shows where unsaved changes are-The tab SHALL show the path of changes as three stages, source, Databasus and storage, with:+The technical details section SHALL show the path of changes as three stages, source, Databasus and storage, with:- at the source: what is not received by Databasus yet, against the rebuild lag and, when the source sets a limit, the remaining allowance;- in Databasus: the local queue, against the size at which the receiver is paused, and whether receiving is paused;- in storage: how long ago the newest WAL segment was archived;-- between the stages: the source's write rate and the archive rate.+- between the stages: the source's write rate and the archive rate, on a connector that points to the next stage.-An amount above its limit SHALL show as over the limit, not as a full bar. Each stage SHALL take the color of the most severe reason about it. Each amount on a stage SHALL offer a short explanation on hover or keyboard focus. On a narrow screen the stages SHALL stack vertically.+The stages SHALL sit in one frame as nodes of a single line, each with an icon and its name, and each rate SHALL sit on the line between two nodes, like the throughput of a pipe, with its name and the color of its chart line under it. Under the nodes the section SHALL say that the rates are averages over the last 10 minutes and the amounts are current.++Each stage SHALL show its amount under a short label. An empty amount SHALL read as nothing waiting, with a success icon, instead of 0 B over an empty meter. An amount above zero SHALL show as a number and, when it has a limit, say how much of the limit it is, such as "300 MB of 512 MB", next to a thin meter; the limit's sentence, such as the size at which receiving pauses, SHALL appear only then and otherwise stay in the explanation on hover or keyboard focus. An amount above its limit SHALL show as over the limit, not as a full bar. A stage without a problem SHALL stay neutral; a stage with a problem SHALL take the color of the most severe reason about that stage on its icon, together with an icon and the word for that level, so color is never the only signal. The WAL chain broken reason concerns the backup history rather than a stage, so it SHALL color no stage. Each amount on a stage SHALL offer a short explanation on hover or keyboard focus. When the section is wide enough the stages SHALL sit in a row joined by arrows pointing right; otherwise they SHALL stack vertically joined by arrows pointing down. Only one arrow direction SHALL be visible at a time.#### Scenario: Backlog in the local queue- **WHEN** the slot lag is small and the local queue holds 300 MB of its 512 MB pause size for two samples-- **THEN** the Databasus stage shows 300 MB of 512 MB in the needs-attention color-- **AND** the source stage stays in the healthy color+- **THEN** the Databasus stage shows 300 MB of 512 MB in the needs-attention color with its icon and word+- **AND** the source stage stays neutral++#### Scenario: Database writing in bursts++- **WHEN** the database writes a burst every three minutes, each burst reaches storage within seconds, and the average write rate over 10 minutes is 54.6 KB/s+- **THEN** the source and Databasus stages say that nothing is waiting+- **AND** the links show 54.6 KB/s+- **AND** the section says that the rates are averages over the last 10 minutes and the amounts are current++#### Scenario: Broken chain with healthy stages++- **WHEN** the only reason is the WAL chain broken reason and the newest segment was archived seconds ago+- **THEN** every stage stays neutral, without a problem icon++#### Scenario: Wide screen++- **WHEN** the path of changes has room for its stages in a row+- **THEN** each link between stages shows one arrow pointing right and no arrow pointing down++#### Scenario: Narrow screen++- **WHEN** the path of changes has no room for its stages in a row+- **THEN** the stages stack vertically+- **AND** each link between stages shows one arrow pointing down and no arrow pointing right### Requirement: The Monitoring tab shows charts for the selected period-The tab SHALL offer the last hour, day and week, and show for the selected period:+The tab SHALL offer the last hour, day and week, and show one chart for the selected period below the figures: the source write rate and the archive rate. The technical details section SHALL show, for the same period:-- the source write rate and the archive rate on one chart;- what is not saved to storage yet and what is not received by Databasus yet on one chart;- the local queue size with its pause size, and receiver restarts and pauses.-Axes SHALL show formatted amounts and local times. Hovering a time on one chart SHALL mark the same time on the others and show the formatted values. Intervals without samples SHALL show as gaps. When the series holds no point with values, the tab SHALL say that charts appear after a few minutes of streaming instead of showing empty charts. When the data starts inside the period, the tab SHALL say since when it has data.+Axes SHALL show formatted amounts and local times. The amount axis SHALL mark round amounts in the unit it shows, such as 256 KB, 512 KB and 768 KB, not fractions of another unit. Each chart SHALL show its title, its legend and, for the main chart, the period switch in one header above the plot. The plot SHALL keep a fixed height, because the tab itself has a maximum width. Hovering a time on one chart SHALL mark the same time on the others and show the formatted values. When the source write rate and the archive rate are equal, both lines SHALL stay distinguishable.-A details section, collapsed by default, SHALL show the raw values with their technical names: the slot's status, the remaining allowance, the average and longest segment write, the upload concurrency, the ratio of WAL to stored bytes, the WAL segment size and the streaming session's start.+Intervals without samples SHALL show as gaps. A run of two or more intervals without samples after the data starts SHALL be shaded on the chart, and the tab SHALL say from when to when there are no measurements.++A chart SHALL appear only when the series holds at least four points with values. Otherwise the tab SHALL say that there is not enough data for this period yet and that a shorter period may already have a chart. When the data starts inside the period, the time axis SHALL start at the first point with values and the tab SHALL say since when it has data. The amount axis SHALL reach at least 64 KiB/s on the rate chart and at least one WAL segment on the amount charts, so small values stay near the bottom instead of filling the chart.++The technical details section SHALL also show the raw values with their technical names: the slot's status, the remaining allowance, the average and longest segment write, the upload concurrency, the ratio of WAL to stored bytes, the WAL segment size and the streaming session's start.#### Scenario: Archiving falls behind on the chart- **WHEN** every point of the hour holds a source write rate of 21 MB/s and an archive rate of 12 MB/s, and a rising unarchived amount- **THEN** the archive series lies below the source series at every point-- **AND** the not-saved-yet series rises across the hour+- **AND** the not-saved-yet series in the technical details rises across the hour#### Scenario: No history yet- **WHEN** the verdict is collecting data and the series holds no point with values-- **THEN** the tab shows the explanation instead of the charts+- **THEN** the tab shows the explanation instead of the chart++#### Scenario: Two minutes of data++- **WHEN** streaming started two minutes ago and the hour series holds two points with values+- **THEN** the tab shows the explanation instead of the chart++#### Scenario: Data started inside the period++- **WHEN** the hour series holds values only for its last 20 minutes+- **THEN** the chart's time axis starts 20 minutes ago+- **AND** the tab says since when it has data++#### Scenario: Measurements missing for five minutes++- **WHEN** the hour series has values except for five consecutive one-minute points in its middle+- **THEN** the chart shades those five minutes+- **AND** the tab says that there are no measurements from the first to the last of them++#### Scenario: Round rate ticks++- **WHEN** the rate axis reaches 1 MiB/s+- **THEN** its ticks read 0 B/s, 256 KB/s, 512 KB/s, 768 KB/s and 1 MB/s++#### Scenario: Equal rates++- **WHEN** the database writes and Databasus saves at the same rate at every point+- **THEN** both lines are visible on the chart++#### Scenario: Quiet database++- **WHEN** every point of the hour holds a source write rate of 2 KB/s+- **THEN** the rate axis reaches at least 64 KB/s and the line stays near its bottom### Requirement: The Monitoring tab stays current without disturbing the reader-The tab SHALL refresh every 30 seconds in every period while it is open and the browser tab is visible. It SHALL refresh at once when the browser tab becomes visible again and when the period changes.+The tab SHALL read the current values every second, and the full statistics every 30 seconds, in every period while it is open and the browser tab is visible. It SHALL refresh both at once when the browser tab becomes visible again, and the statistics when the period changes. The figures, the restore timeline's end, the path of changes and the time of the newest measurement SHALL use the current values while they are newer than the newest sample. While the latest restorable moment of the statistics equals their newest save, the banner's restorable moment and the end of the newest restorable stretch SHALL follow the newest save of the current values, so the banner never names an older moment than the figure next to it; the verdict, the keeping-up summary, the rates and the charts SHALL use the statistics.-The tab SHALL show the age of the newest sample, updated every second, and mark it as live only while that sample is younger than 2 minutes. When the last successful refresh is older than 2 minutes, the headline SHALL turn neutral gray and say that the current state cannot be confirmed, with the last known verdict and its age.+The tab SHALL show the age of the newest measurement, updated every second, and mark it as live only while that measurement is younger than 2 minutes. When the last successful refresh of the statistics is older than 2 minutes, the headline SHALL turn neutral gray and say that the current state cannot be confirmed, with the last known verdict and its age. A failed reading of the current values SHALL leave the values of the statistics on screen without an error of its own.-A refresh SHALL keep the previous content on screen until the new content arrives, keep the scroll position and the selected period, and not replay the charts' entry animation. Changed numbers and the headline color SHALL change with a short transition. When the reader's system asks for reduced motion, there SHALL be no transitions, no pulsing and no chart animation. A failed refresh SHALL keep the last content, say that refreshing failed, and keep retrying on the same schedule. A failed first load SHALL show the error and a retry button.+A refresh SHALL keep the previous content on screen until the new content arrives, keep the scroll position and the selected period, and not replay the charts' entry animation. Changed numbers and the headline color SHALL change with a short transition. When the reader's system asks for reduced motion, there SHALL be no transitions, no pulsing and no chart animation. A failed refresh of the statistics SHALL keep the last content, say that refreshing failed, and keep retrying on the same schedule. A failed first load SHALL show the error and a retry button.#### Scenario: Status changes while open- **WHEN** the tab is open on the day view and the verdict changes from healthy to needs attention- **THEN** the headline changes within 30 seconds without reloading the page+#### Scenario: Buffer drains while open++- **WHEN** the local queue drains while the tab is open+- **THEN** the path of changes shows the new amount within about a second++#### Scenario: Segment saved between two statistics refreshes++- **WHEN** the latest restorable moment equals the newest save and a new segment reaches storage 5 seconds after the statistics refresh+- **THEN** within about a second the banner names the new save's time as the moment the database can be restored to+#### Scenario: Browser tab hidden- **WHEN** the browser tab is hidden for ten minutes and then shown again@@ -566,3 +677,256 @@ A refresh SHALL keep the previous content on screen until the new content arrive- **WHEN** refreshes have failed for 3 minutes after a healthy response- **THEN** the headline is gray and says the state cannot be confirmed, last known healthy 3 minutes ago++### Requirement: The statistics state what the backups can restore++The statistics SHALL state the latest moment to which the database's backups can restore it at the time of the request. That moment SHALL be the one a restore to the latest available point reaches. It starts from the newest completed backup of the newest chain, full or incremental, and extends through the WAL that follows that backup without a gap. With WAL after that backup, it is the time Databasus received the last segment before the first gap after that backup, or the newest segment when there is no such gap. Without WAL after that backup, it is the backup's completion time. When no full backup has completed, the statistics SHALL state that no moment can be restored yet.++The statistics SHALL also state the stretches of time the newest chain can restore to, oldest first. Each completed backup of that chain, full or incremental, opens a stretch from its completion time to the moment the WAL after it reaches without a gap, by the same rule as above. Stretches that overlap or touch SHALL be merged. A WAL segment that is still being uploaded SHALL end a stretch like a gap. The last stretch SHALL end at the latest restorable moment. Without a completed full backup, the list SHALL be empty.++#### Scenario: Streaming without gaps++- **WHEN** the newest full backup completed yesterday and every WAL segment since then is archived without a gap+- **THEN** the latest restorable moment is the time Databasus received the newest archived segment++#### Scenario: Gap in the newest chain++- **WHEN** the slot was rebuilt at 07:51, which left a WAL gap after the segment received at 07:50, no backup completed after the gap, and segments after the gap keep arriving+- **THEN** the latest restorable moment is 07:50+- **AND** a restore to the latest available point reaches the same moment++#### Scenario: Incremental backup after the gap++- **WHEN** the newest chain has a WAL gap at 07:51, an incremental backup of that chain completed at 09:00, and every segment after 09:00 is archived without a gap+- **THEN** the latest restorable moment is the time Databasus received the newest archived segment+- **AND** the restorable stretches are two: from the full backup's completion to 07:50, and from 09:00 to the newest archived segment++#### Scenario: Incremental backup before the gap++- **WHEN** an incremental backup of the newest chain completed at 06:00, and the chain has a WAL gap at 07:51 with segments after it+- **THEN** the latest restorable moment is the time Databasus received the last segment before the gap+- **AND** the restorable stretches are one, from the full backup's completion to that moment++#### Scenario: Newer full backup++- **WHEN** an older chain has a gap, and a newer full backup completed after it+- **THEN** the restorable stretches start at the newer full backup's completion++#### Scenario: Full backup without WAL after it++- **WHEN** the only completed full backup finished at 14:02 and no WAL segment followed it+- **THEN** the latest restorable moment is 14:02++#### Scenario: No full backup yet++- **WHEN** no full backup of the database has completed+- **THEN** the statistics state that no moment can be restored yet+- **AND** the restorable stretches are empty++### Requirement: The Monitoring tab says to which moment the database can be restored++The verdict banner SHALL say, in one sentence, to which moment the database can be restored:++- when a moment is known and the WAL chain broken reason is listed: until a new full backup finishes, the database can be restored only up to that moment;+- when a moment is known, that reason is not listed and the newest restorable stretch covers the whole history: the database can be restored to any moment up to that moment;+- when a moment is known, that reason is not listed and an earlier stretch cannot be restored: the database can be restored to any moment from the start of the newest restorable stretch up to that moment, so the sentence never promises the moments the timeline marks as lost;+- when no moment can be restored yet and a full backup is requested or running: nothing can be restored until the first full backup finishes, which is on its way;+- when no moment can be restored yet and no full backup is requested or running: nothing can be restored yet, because no full backup has finished.++The moment SHALL be shown as a local time for today and as a local date and time otherwise, followed by how long ago it was, rounded for reading. When that age cannot be computed, the sentence SHALL leave it out instead of showing an invalid number. The sentence SHALL appear for every verdict, collecting data included, and SHALL keep the last known moment while the current state cannot be confirmed.++#### Scenario: Healthy database++- **WHEN** the verdict is healthy and the latest restorable moment was 30 seconds ago+- **THEN** the banner says that the database can be restored to any moment up to that time, 30 seconds ago++#### Scenario: Broken chain++- **WHEN** the WAL chain broken reason is listed, the latest restorable moment is 07:50 today and the newest segment was archived at 07:58+- **THEN** the banner says that until a new full backup finishes, the database can be restored only up to 07:50++#### Scenario: Broken chain repaired by an incremental backup++- **WHEN** an incremental backup after the gap brought the latest restorable moment up to the newest archived segment+- **THEN** the WAL chain broken reason is not listed+- **AND** the banner says that the database can be restored to any moment up to that moment++#### Scenario: Old gap before the newest restorable stretch++- **WHEN** the database cannot be restored to moments between Oct 10 18:35 and Oct 20 07:51, and can be restored to every moment after that up to 08:32 today+- **THEN** the banner says that the database can be restored to any moment from Oct 20 07:51 up to 08:32++#### Scenario: Just enabled++- **WHEN** the verdict is collecting data and no full backup has completed or is requested+- **THEN** the banner says that nothing can be restored yet because no full backup has finished++#### Scenario: Saving stuck++- **WHEN** no new changes have reached storage for 40 minutes while the database keeps writing+- **THEN** the restore sentence names a moment about 40 minutes ago++#### Scenario: Before the first full backup++- **WHEN** no full backup has completed and none is requested or running+- **THEN** the banner says that nothing can be restored yet because no full backup has finished++### Requirement: The Monitoring tab offers to start a full backup when that is the fix++When a full backup is what repairs the situation, the verdict banner SHALL offer a button that starts one. That is the case while all of these hold:++- the verdict is healthy, needs attention or broken, and the current state is confirmed;+- the WAL chain broken reason or the slot missing reason is listed, or no full backup has completed;+- no full backup is requested or running.++The not streaming verdict SHALL never offer the button, because Databasus takes no backups while streaming is off. The collecting data verdict SHALL not offer it either: it lasts at most two minutes, and the restore sentence already says whether a first full backup exists.++The button SHALL request a full backup at once, the same way the Backups tab does. While the request runs, the button SHALL show that it is working and SHALL not accept another click. After the request succeeds, the tab SHALL refresh at once, so the banner says that a full backup is on its way without waiting for the next scheduled refresh. A failed request SHALL show the error and leave the button available.++#### Scenario: Broken chain fixed from the tab++- **WHEN** a user who may manage the database sees the WAL chain broken reason with no full backup pending, and presses the button+- **THEN** a full backup is requested+- **AND** the banner says that a full backup is on its way++#### Scenario: Full backup already pending++- **WHEN** the WAL chain broken reason is listed and a full backup is requested or running+- **THEN** the banner offers no button+- **AND** says that a new full backup is on its way++#### Scenario: Request refused++- **WHEN** the full backup request fails+- **THEN** the tab shows the error+- **AND** the button can be pressed again++#### Scenario: Missing slot++- **WHEN** a user who may manage the database sees the slot missing reason with no full backup pending+- **THEN** the banner offers the full backup button++#### Scenario: Healthy streaming before the first full backup++- **WHEN** the verdict is healthy, no full backup has completed and none is requested or running+- **THEN** the banner offers the full backup button++#### Scenario: Streaming off++- **WHEN** the verdict is not streaming because backups are disabled, and no full backup has completed+- **THEN** the banner offers no full backup button++### Requirement: Only users who may manage the database can start a full backup from the Monitoring tab++The full backup button SHALL be shown only to users who may manage the database's backups. A user who can only view the database SHALL see the problem and the sentence about what to do, without the button. A full backup request from such a user SHALL be refused by the API, whatever the tab shows.++#### Scenario: Read-only member++- **WHEN** a workspace member who can view but not manage the database opens the tab while the chain is broken+- **THEN** the banner shows the problem and what to do+- **AND** offers no full backup button++#### Scenario: Request without permission++- **WHEN** a user who cannot manage the database requests a full backup through the API+- **THEN** the request is refused+- **AND** no full backup is requested++### Requirement: The Monitoring tab shows the current flow as four figures++Under the verdict banner, the tab SHALL show four figures from the newest statistics, each as a label with a large value:++- when the last change was saved to storage, as a relative time, or that nothing is saved yet;+- how much is waiting to be saved to storage;+- how fast the database writes changes;+- how fast Databasus saves them.++The two rates SHALL use the same names and colors as the lines of the main chart, so a reader can match a figure to its line, and SHALL say that they are averages over the last 10 minutes, so a rate next to an empty queue does not read as a contradiction.++The figures SHALL be shown for the healthy, needs attention and broken verdicts, and while the current state cannot be confirmed, and not for the collecting data and not streaming verdicts. A value that is not known SHALL be shown as not measured, not as zero.++#### Scenario: Busy healthy database++- **WHEN** the database writes 10 MB/s, Databasus saves 10 MB/s, 20 MB is not saved yet and the newest segment was archived 15 seconds ago+- **THEN** the figures show 15 seconds ago, 20 MB, 10 MB/s of database writes and 10 MB/s saved to storage++#### Scenario: No write rate yet++- **WHEN** the window of the last 10 minutes holds no sample with a source write value+- **THEN** both rate figures say not measured++### Requirement: The Monitoring tab shows tips and technical detail below the chart++Notices other than the no full backup yet notice SHALL appear as tips: quiet notes, each with its title and two sentences, inside the technical details section under the path of changes. The no full backup yet notice SHALL be shown only through the banner's restore sentence, which appears for every verdict. A tip SHALL never use a warning or error color. The no slot WAL limit tip SHALL explain in plain words what the limit protects and what it costs.++Everything else SHALL sit in one technical details section below the chart, with its own heading and shown without a click: the path of changes, the tips, the chart of what is not saved and not received yet, the buffer chart, and the raw values.++#### Scenario: Default source settings++- **WHEN** the source sets no limit on WAL kept for the slot and nothing else is wrong+- **THEN** the technical details section shows one tip with its text++#### Scenario: Engineer looks for raw values++- **WHEN** a reader scrolls below the main chart+- **THEN** the technical details section shows the path of changes, the two additional charts and the raw values++### Requirement: The Monitoring tab shows which moments can be restored++Under the figures, the tab SHALL show a timeline of the newest chain, from the start of its first restorable stretch to now. The timeline SHALL mark the restorable stretches, the stretches between them that cannot be restored, and the time after the latest restorable moment that is not saved yet, in different colors and patterns. A stretch that cannot be restored SHALL stay visible however short it is compared with the whole timeline. Under the timeline, the tab SHALL name each stretch that cannot be restored, up to three, in a sentence with its start and end, so color is not the only signal. The timeline SHALL not appear when the statistics list no restorable stretch.++#### Scenario: Old gap bridged by an incremental backup++- **WHEN** the newest chain cannot restore to moments between Oct 10 18:35 and Oct 20 07:51, and can restore to every moment after that up to a minute ago+- **THEN** the banner is green+- **AND** the timeline marks the stretch from Oct 10 18:35 to Oct 20 07:51 as not restorable+- **AND** a sentence under it says that the database cannot be restored to moments between those times++#### Scenario: No full backup yet++- **WHEN** no full backup has completed+- **THEN** the tab shows no timeline++### Requirement: The Monitoring tab reads well on wide screens++The tab SHALL stop growing at a maximum width of about 1150 px, so on wide screens the text, the figures and the charts keep the sizes they have on a laptop instead of stretching. The banner's text SHALL keep a readable line length, the figures SHALL sit in cards next to each other, and the charts SHALL keep a fixed height. The path of changes SHALL put its stages in a row only when its own section is wide enough for them, and stack them otherwise.++#### Scenario: 2560 px wide screen++- **WHEN** the tab is shown in a 2560 px wide window+- **THEN** the tab is no wider than in a 1600 px wide window+- **AND** the four figures sit in one row of cards++#### Scenario: Laptop screen++- **WHEN** the tab is shown in a 1240 px wide window next to the sidebar+- **THEN** the stages of the path of changes sit in one row without horizontal scrolling++### Requirement: The API serves the current values every second++A second authenticated endpoint SHALL return the current values of a database's running WAL stream, read from the running streamer at the time of the request and not stored: the time of the reading, the local queue and its pause size, whether receiving runs, the archive progress point, the time the newest WAL segment was archived, and how much is not saved to storage yet. The values from the source database, its current position, the slot's status, the slot lag and the remaining allowance, SHALL come from the newest probe of the source that the streamer already makes, at least every 10 seconds, together with the time of that probe; the endpoint SHALL not open a connection to the source itself. Only users who can view the database SHALL read it. While no streamer runs for the database, the response SHALL say so and carry no values.++#### Scenario: Buffer drains between two samples++- **WHEN** the local queue drains from 300 MB to 0 B within five seconds+- **THEN** a request one second later reports 0 B in the local queue++#### Scenario: Source values follow the probe++- **WHEN** the newest source probe ran 7 seconds ago+- **THEN** the source-side values are those of that probe, with its time++#### Scenario: Saving moves past the probed position++- **WHEN** segments reached storage after the newest source probe, past the source position it found+- **THEN** the response says that nothing is waiting to be saved, not that the amount is unknown++#### Scenario: Streamer not running++- **WHEN** WAL streaming is off for the database+- **THEN** the response says that no streamer runs and carries no values++#### Scenario: Member without access++- **WHEN** a user who cannot view the database requests its current values+- **THEN** the request is refused