PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FIX (mariadb\mysql): Count backup size after compression
Rostislav Dugincbf740fd7589
diff --git a/backend/internal/features/backups/backups/usecases/logical/mariadb/create_backup_uc.go b/backend/internal/features/backups/backups/usecases/logical/mariadb/create_backup_uc.goindex d2be4bf8..4a492777 100644--- a/backend/internal/features/backups/backups/usecases/logical/mariadb/create_backup_uc.go+++ b/backend/internal/features/backups/backups/usecases/logical/mariadb/create_backup_uc.go@@ -56,6 +56,13 @@ type writeResult struct {writeErr error}+type compressedCopySpec struct {+ Destination io.Writer+ Source io.Reader+ CompressedBytesCounter *io_utils.CountingWriter+ ProgressListener func(completedMBs float64)+}+func (uc *CreateMariadbBackupUsecase) Execute(ctx context.Context,backup *backups_core_logical.LogicalBackup,@@ -222,12 +229,13 @@ func (uc *CreateMariadbBackupUsecase) streamToStorage(return nil, err}- zstdWriter, err := zstd.NewWriter(finalWriter,+ compressedBytesCounter := io_utils.NewCountingWriter(finalWriter)++ zstdWriter, err := zstd.NewWriter(compressedBytesCounter,zstd.WithEncoderLevel(zstd.EncoderLevelFromZstd(zstdStorageCompressionLevel)))if err != nil {return nil, fmt.Errorf("failed to create zstd writer: %w", err)}- countingWriter := io_utils.NewCountingWriter(zstdWriter)saveErrCh := make(chan error, 1)go func() {@@ -250,20 +258,16 @@ func (uc *CreateMariadbBackupUsecase) streamToStorage(}copyResultCh := make(chan error, 1)- bytesWrittenCh := make(chan int64, 1)go func() {- bytesWritten, err := uc.copyWithShutdownCheck(- ctx,- countingWriter,- pgStdout,- backupProgressListener,- )- bytesWrittenCh <- bytesWritten- copyResultCh <- err+ copyResultCh <- uc.copyWithShutdownCheck(ctx, compressedCopySpec{+ Destination: zstdWriter,+ Source: pgStdout,+ CompressedBytesCounter: compressedBytesCounter,+ ProgressListener: backupProgressListener,+ })}()copyErr := <-copyResultCh- bytesWritten := <-bytesWrittenChwaitErr := cmd.Wait()select {@@ -296,8 +300,8 @@ func (uc *CreateMariadbBackupUsecase) streamToStorage(stderrOutput := <-stderrChif waitErr == nil && copyErr == nil && saveErr == nil && backupProgressListener != nil {- sizeMB := float64(bytesWritten) / (1024 * 1024)- backupProgressListener(sizeMB)+ compressedSizeMB := float64(compressedBytesCounter.GetBytesWritten()) / (1024 * 1024)+ backupProgressListener(compressedSizeMB)}switch {@@ -354,30 +358,27 @@ port=%dfunc (uc *CreateMariadbBackupUsecase) copyWithShutdownCheck(ctx context.Context,- dst io.Writer,- src io.Reader,- backupProgressListener func(completedMBs float64),-) (int64, error) {+ copySpec compressedCopySpec,+) error {buf := make([]byte, copyBufferSize)- var totalBytesWritten int64var lastReportedMB float64for {select {case <-ctx.Done():- return totalBytesWritten, fmt.Errorf("copy cancelled: %w", ctx.Err())+ return fmt.Errorf("copy cancelled: %w", ctx.Err())default:}if config.IsShouldShutdown() {- return totalBytesWritten, fmt.Errorf("copy cancelled due to shutdown")+ return fmt.Errorf("copy cancelled due to shutdown")}- bytesRead, readErr := src.Read(buf)+ bytesRead, readErr := copySpec.Source.Read(buf)if bytesRead > 0 {writeResultCh := make(chan writeResult, 1)go func() {- bytesWritten, writeErr := dst.Write(buf[0:bytesRead])+ bytesWritten, writeErr := copySpec.Destination.Write(buf[0:bytesRead])writeResultCh <- writeResult{bytesWritten, writeErr}}()@@ -386,7 +387,7 @@ func (uc *CreateMariadbBackupUsecase) copyWithShutdownCheck(select {case <-ctx.Done():- return totalBytesWritten, fmt.Errorf("copy cancelled during write: %w", ctx.Err())+ return fmt.Errorf("copy cancelled during write: %w", ctx.Err())case result := <-writeResultCh:bytesWritten = result.bytesWrittenwriteErr = result.writeErr@@ -400,33 +401,33 @@ func (uc *CreateMariadbBackupUsecase) copyWithShutdownCheck(}if writeErr != nil {- return totalBytesWritten, writeErr+ return writeErr}if bytesRead != bytesWritten {- return totalBytesWritten, io.ErrShortWrite+ return io.ErrShortWrite}- totalBytesWritten += int64(bytesWritten)-- if backupProgressListener != nil {- currentSizeMB := float64(totalBytesWritten) / (1024 * 1024)- if currentSizeMB >= lastReportedMB+progressReportIntervalMB {- backupProgressListener(currentSizeMB)- lastReportedMB = currentSizeMB+ if copySpec.ProgressListener != nil {+ compressedSizeMB := float64(+ copySpec.CompressedBytesCounter.GetBytesWritten(),+ ) / (1024 * 1024)+ if compressedSizeMB >= lastReportedMB+progressReportIntervalMB {+ copySpec.ProgressListener(compressedSizeMB)+ lastReportedMB = compressedSizeMB}}}if readErr != nil {if readErr != io.EOF {- return totalBytesWritten, readErr+ return readErr}break}}- return totalBytesWritten, nil+ return nil}func (uc *CreateMariadbBackupUsecase) createBackupContext(diff --git a/backend/internal/features/backups/backups/usecases/logical/mongodb/create_backup_uc.go b/backend/internal/features/backups/backups/usecases/logical/mongodb/create_backup_uc.goindex 9beed0e9..9ced8169 100644--- a/backend/internal/features/backups/backups/usecases/logical/mongodb/create_backup_uc.go+++ b/backend/internal/features/backups/backups/usecases/logical/mongodb/create_backup_uc.go@@ -23,7 +23,6 @@ import (encryption_secrets "databasus-backend/internal/features/encryption/secrets""databasus-backend/internal/features/storages""databasus-backend/internal/util/encryption"- io_utils "databasus-backend/internal/util/io""databasus-backend/internal/util/tools")@@ -185,8 +184,6 @@ func (uc *CreateMongodbBackupUsecase) streamToStorage(return nil, err}- countingWriter := io_utils.NewCountingWriter(finalWriter)-saveErrCh := make(chan error, 1)go func() {saveErr := storage.SaveFile(@@ -212,7 +209,7 @@ func (uc *CreateMongodbBackupUsecase) streamToStorage(go func() {bytesWritten, copyErr := uc.copyWithShutdownCheck(ctx,- countingWriter,+ finalWriter,pgStdout,backupProgressListener,)diff --git a/backend/internal/features/backups/backups/usecases/logical/mysql/create_backup_uc.go b/backend/internal/features/backups/backups/usecases/logical/mysql/create_backup_uc.goindex abdae4eb..380507c6 100644--- a/backend/internal/features/backups/backups/usecases/logical/mysql/create_backup_uc.go+++ b/backend/internal/features/backups/backups/usecases/logical/mysql/create_backup_uc.go@@ -56,6 +56,13 @@ type writeResult struct {writeErr error}+type compressedCopySpec struct {+ Destination io.Writer+ Source io.Reader+ CompressedBytesCounter *io_utils.CountingWriter+ ProgressListener func(completedMBs float64)+}+func (uc *CreateMysqlBackupUsecase) Execute(ctx context.Context,backup *backups_core_logical.LogicalBackup,@@ -241,12 +248,13 @@ func (uc *CreateMysqlBackupUsecase) streamToStorage(return nil, err}- zstdWriter, err := zstd.NewWriter(finalWriter,+ compressedBytesCounter := io_utils.NewCountingWriter(finalWriter)++ zstdWriter, err := zstd.NewWriter(compressedBytesCounter,zstd.WithEncoderLevel(zstd.EncoderLevelFromZstd(zstdStorageCompressionLevel)))if err != nil {return nil, fmt.Errorf("failed to create zstd writer: %w", err)}- countingWriter := io_utils.NewCountingWriter(zstdWriter)saveErrCh := make(chan error, 1)go func() {@@ -269,20 +277,16 @@ func (uc *CreateMysqlBackupUsecase) streamToStorage(}copyResultCh := make(chan error, 1)- bytesWrittenCh := make(chan int64, 1)go func() {- bytesWritten, err := uc.copyWithShutdownCheck(- ctx,- countingWriter,- pgStdout,- backupProgressListener,- )- bytesWrittenCh <- bytesWritten- copyResultCh <- err+ copyResultCh <- uc.copyWithShutdownCheck(ctx, compressedCopySpec{+ Destination: zstdWriter,+ Source: pgStdout,+ CompressedBytesCounter: compressedBytesCounter,+ ProgressListener: backupProgressListener,+ })}()copyErr := <-copyResultCh- bytesWritten := <-bytesWrittenChwaitErr := cmd.Wait()select {@@ -315,8 +319,8 @@ func (uc *CreateMysqlBackupUsecase) streamToStorage(stderrOutput := <-stderrChif waitErr == nil && copyErr == nil && saveErr == nil && backupProgressListener != nil {- sizeMB := float64(bytesWritten) / (1024 * 1024)- backupProgressListener(sizeMB)+ compressedSizeMB := float64(compressedBytesCounter.GetBytesWritten()) / (1024 * 1024)+ backupProgressListener(compressedSizeMB)}switch {@@ -373,30 +377,27 @@ port=%dfunc (uc *CreateMysqlBackupUsecase) copyWithShutdownCheck(ctx context.Context,- dst io.Writer,- src io.Reader,- backupProgressListener func(completedMBs float64),-) (int64, error) {+ copySpec compressedCopySpec,+) error {buf := make([]byte, copyBufferSize)- var totalBytesWritten int64var lastReportedMB float64for {select {case <-ctx.Done():- return totalBytesWritten, fmt.Errorf("copy cancelled: %w", ctx.Err())+ return fmt.Errorf("copy cancelled: %w", ctx.Err())default:}if config.IsShouldShutdown() {- return totalBytesWritten, fmt.Errorf("copy cancelled due to shutdown")+ return fmt.Errorf("copy cancelled due to shutdown")}- bytesRead, readErr := src.Read(buf)+ bytesRead, readErr := copySpec.Source.Read(buf)if bytesRead > 0 {writeResultCh := make(chan writeResult, 1)go func() {- bytesWritten, writeErr := dst.Write(buf[0:bytesRead])+ bytesWritten, writeErr := copySpec.Destination.Write(buf[0:bytesRead])writeResultCh <- writeResult{bytesWritten, writeErr}}()@@ -405,7 +406,7 @@ func (uc *CreateMysqlBackupUsecase) copyWithShutdownCheck(select {case <-ctx.Done():- return totalBytesWritten, fmt.Errorf("copy cancelled during write: %w", ctx.Err())+ return fmt.Errorf("copy cancelled during write: %w", ctx.Err())case result := <-writeResultCh:bytesWritten = result.bytesWrittenwriteErr = result.writeErr@@ -419,33 +420,33 @@ func (uc *CreateMysqlBackupUsecase) copyWithShutdownCheck(}if writeErr != nil {- return totalBytesWritten, writeErr+ return writeErr}if bytesRead != bytesWritten {- return totalBytesWritten, io.ErrShortWrite+ return io.ErrShortWrite}- totalBytesWritten += int64(bytesWritten)-- if backupProgressListener != nil {- currentSizeMB := float64(totalBytesWritten) / (1024 * 1024)- if currentSizeMB >= lastReportedMB+progressReportIntervalMB {- backupProgressListener(currentSizeMB)- lastReportedMB = currentSizeMB+ if copySpec.ProgressListener != nil {+ compressedSizeMB := float64(+ copySpec.CompressedBytesCounter.GetBytesWritten(),+ ) / (1024 * 1024)+ if compressedSizeMB >= lastReportedMB+progressReportIntervalMB {+ copySpec.ProgressListener(compressedSizeMB)+ lastReportedMB = compressedSizeMB}}}if readErr != nil {if readErr != io.EOF {- return totalBytesWritten, readErr+ return readErr}break}}- return totalBytesWritten, nil+ return nil}func (uc *CreateMysqlBackupUsecase) createBackupContext(diff --git a/backend/internal/features/backups/backups/usecases/logical/postgresql/create_backup_uc.go b/backend/internal/features/backups/backups/usecases/logical/postgresql/create_backup_uc.goindex dac8718b..e7eee778 100644--- a/backend/internal/features/backups/backups/usecases/logical/postgresql/create_backup_uc.go+++ b/backend/internal/features/backups/backups/usecases/logical/postgresql/create_backup_uc.go@@ -26,7 +26,6 @@ import (encryption_secrets "databasus-backend/internal/features/encryption/secrets""databasus-backend/internal/features/storages""databasus-backend/internal/util/encryption"- io_utils "databasus-backend/internal/util/io""databasus-backend/internal/util/tools")@@ -190,11 +189,6 @@ func (uc *CreatePostgresqlBackupUsecase) streamToStorage(return nil, err}- countingWriter := io_utils.NewCountingWriter(finalWriter)-- // The backup ID becomes the object key / filename in storage-- // Start streaming into storage in its own goroutinesaveErrCh := make(chan error, 1)go func() {saveErr := storage.SaveFile(@@ -211,18 +205,16 @@ func (uc *CreatePostgresqlBackupUsecase) streamToStorage(saveErrCh <- saveErr}()- // Start pg_dumpif err = cmd.Start(); err != nil {return nil, fmt.Errorf("start %s: %w", filepath.Base(pgBin), err)}- // Copy pg output directly to storage with shutdown checkscopyResultCh := make(chan error, 1)bytesWrittenCh := make(chan int64, 1)go func() {bytesWritten, err := uc.copyWithShutdownCheck(ctx,- countingWriter,+ finalWriter,pgStdout,backupProgressListener,)diff --git a/backend/internal/features/backups/backups/usecases/physical/postgresql/byte_stall.go b/backend/internal/features/backups/backups/usecases/physical/postgresql/byte_stall.goindex b3a315ad..12b3efb3 100644--- a/backend/internal/features/backups/backups/usecases/physical/postgresql/byte_stall.go+++ b/backend/internal/features/backups/backups/usecases/physical/postgresql/byte_stall.go@@ -33,11 +33,6 @@ const byteStallPollInterval = 10 * time.Second// suite.const PgBasebackupWaitTimeout = 30 * time.Second-// ByteCounter wraps an io.Writer and tracks bytes written atomically so a-// watcher goroutine can read the count without racing the writer goroutine.-// CountingWriter in util/io is the single-threaded equivalent — physical-// backups need atomic semantics because the byte-stall watcher reads from a-// goroutine separate from the pg_basebackup-to-storage copy.type ByteCounter struct {writer io.Writerbytes atomic.Int64diff --git a/backend/internal/features/tests/logical/mariadb/backup_restore_test.go b/backend/internal/features/tests/logical/mariadb/backup_restore_test.goindex 4b6d9aac..17eb637b 100644--- a/backend/internal/features/tests/logical/mariadb/backup_restore_test.go+++ b/backend/internal/features/tests/logical/mariadb/backup_restore_test.go@@ -152,6 +152,7 @@ func testMariadbBackupRestoreForVersion(backup := logicaltesting.WaitForBackupCompletion(t, router, database.ID, user.Token, 5*time.Minute)assert.Equal(t, backups_core_logical.BackupStatusCompleted, backup.Status)+ logicaltesting.AssertBackupSizeMatchesDownloadedBytes(t, router, backup, user.Token)newDBName := "restoreddb_mariadb"_, err = container.DB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s;", newDBName))@@ -249,6 +250,7 @@ func testMariadbBackupRestoreWithEncryptionForVersion(backup := logicaltesting.WaitForBackupCompletion(t, router, database.ID, user.Token, 5*time.Minute)assert.Equal(t, backups_core_logical.BackupStatusCompleted, backup.Status)assert.Equal(t, backups_core_enums.BackupEncryptionEncrypted, backup.Encryption)+ logicaltesting.AssertBackupSizeMatchesDownloadedBytes(t, router, backup, user.Token)newDBName := "restoreddb_mariadb_encrypted"_, err = container.DB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s;", newDBName))diff --git a/backend/internal/features/tests/logical/mongodb/backup_restore_test.go b/backend/internal/features/tests/logical/mongodb/backup_restore_test.goindex 63971eb2..caa659d5 100644--- a/backend/internal/features/tests/logical/mongodb/backup_restore_test.go+++ b/backend/internal/features/tests/logical/mongodb/backup_restore_test.go@@ -125,6 +125,7 @@ func testMongodbBackupRestoreForVersion(backup := logicaltesting.WaitForBackupCompletion(t, router, database.ID, user.Token, 5*time.Minute)assert.Equal(t, backups_core_logical.BackupStatusCompleted, backup.Status)+ logicaltesting.AssertBackupSizeMatchesDownloadedBytes(t, router, backup, user.Token)newDBName := "restoreddb_mongodb_" + uuid.New().String()[:8]diff --git a/backend/internal/features/tests/logical/mysql/backup_restore_test.go b/backend/internal/features/tests/logical/mysql/backup_restore_test.goindex 8e4df065..21fdcdbb 100644--- a/backend/internal/features/tests/logical/mysql/backup_restore_test.go+++ b/backend/internal/features/tests/logical/mysql/backup_restore_test.go@@ -136,6 +136,7 @@ func testMysqlBackupRestoreForVersion(t *testing.T, endpoint containers.Endpointbackup := logicaltesting.WaitForBackupCompletion(t, router, database.ID, user.Token, 5*time.Minute)assert.Equal(t, backups_core_logical.BackupStatusCompleted, backup.Status)+ logicaltesting.AssertBackupSizeMatchesDownloadedBytes(t, router, backup, user.Token)newDBName := "restoreddb_mysql"_, err = container.DB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s;", newDBName))@@ -233,6 +234,7 @@ func testMysqlBackupRestoreWithEncryptionForVersion(backup := logicaltesting.WaitForBackupCompletion(t, router, database.ID, user.Token, 5*time.Minute)assert.Equal(t, backups_core_logical.BackupStatusCompleted, backup.Status)assert.Equal(t, backups_core_enums.BackupEncryptionEncrypted, backup.Encryption)+ logicaltesting.AssertBackupSizeMatchesDownloadedBytes(t, router, backup, user.Token)newDBName := "restoreddb_mysql_encrypted"_, err = container.DB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s;", newDBName))diff --git a/backend/internal/features/tests/logical/postgresql/backup_restore_test.go b/backend/internal/features/tests/logical/postgresql/backup_restore_test.goindex 71909337..d8dc870a 100644--- a/backend/internal/features/tests/logical/postgresql/backup_restore_test.go+++ b/backend/internal/features/tests/logical/postgresql/backup_restore_test.go@@ -193,6 +193,7 @@ func testBackupRestoreForVersion(t *testing.T, endpoint containers.Endpoint, pgVbackup := logicaltesting.WaitForBackupCompletion(t, router, database.ID, user.Token, 5*time.Minute)assert.Equal(t, backups_core_logical.BackupStatusCompleted, backup.Status)+ logicaltesting.AssertBackupSizeMatchesDownloadedBytes(t, router, backup, user.Token)newDBName := fmt.Sprintf("restoreddb_%s_cpu%d_%s", pgVersion, cpuCount, uuid.New().String()[:8])_, err = container.DB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s;", newDBName))diff --git a/backend/internal/features/tests/logical/shared/backups.go b/backend/internal/features/tests/logical/shared/backups.goindex 29ff218a..e11af34b 100644--- a/backend/internal/features/tests/logical/shared/backups.go+++ b/backend/internal/features/tests/logical/shared/backups.go@@ -3,14 +3,17 @@ package logicaltestingimport ("fmt""net/http"+ "strconv""testing""time""github.com/gin-gonic/gin""github.com/google/uuid"+ "github.com/stretchr/testify/require"backups_core_enums "databasus-backend/internal/features/backups/backups/core/enums"backups_core_logical "databasus-backend/internal/features/backups/backups/core/logical"+ "databasus-backend/internal/features/backups/backups/download/download_token"backups_dto_logical "databasus-backend/internal/features/backups/backups/dto/logical"backups_config_logical "databasus-backend/internal/features/backups/config/logical""databasus-backend/internal/features/storages"@@ -160,3 +163,51 @@ func WaitForBackupTerminalStatus(return nil}++// The download endpoint derives Content-Length from BackupSizeMb, so a size that+// disagrees with the delivered body makes every download announce bytes it never+// sends (issue #691).+func AssertBackupSizeMatchesDownloadedBytes(+ t *testing.T,+ router *gin.Engine,+ backup *backups_core_logical.LogicalBackup,+ token string,+) {+ t.Helper()++ var downloadToken download_token.GenerateTokenResponse+ test_utils.MakePostRequestAndUnmarshal(+ t,+ router,+ fmt.Sprintf("/api/v1/backups/%s/download-token", backup.ID.String()),+ "Bearer "+token,+ nil,+ http.StatusOK,+ &downloadToken,+ )++ downloadResponse := test_utils.MakeGetRequest(+ t,+ router,+ fmt.Sprintf("/api/v1/backups/%s/file?token=%s", backup.ID.String(), downloadToken.Token),+ "",+ http.StatusOK,+ )++ downloadedBytes := int64(len(downloadResponse.Body))++ require.Equal(+ t,+ strconv.FormatInt(downloadedBytes, 10),+ downloadResponse.Headers.Get("Content-Length"),+ "announced Content-Length must match the delivered body",+ )++ require.InDelta(+ t,+ float64(downloadedBytes)/(1024*1024),+ backup.BackupSizeMb,+ 0.0001,+ "reported backup size must match the bytes the download endpoint delivers",+ )+}diff --git a/backend/internal/features/tests/logical/shared/router.go b/backend/internal/features/tests/logical/shared/router.goindex 500869d9..15f8b009 100644--- a/backend/internal/features/tests/logical/shared/router.go+++ b/backend/internal/features/tests/logical/shared/router.go@@ -11,11 +11,8 @@ import (workspaces_testing "databasus-backend/internal/features/workspaces/testing")-// CreateTestRouter builds the Gin router wiring the workspace, database, backup-// config, backup and restore controllers used by every logical backup/restore-// test.func CreateTestRouter() *gin.Engine {- return workspaces_testing.CreateTestRouter(+ router := workspaces_testing.CreateTestRouter(workspaces_controllers.GetWorkspaceController(),workspaces_controllers.GetMembershipController(),databases.GetDatabaseController(),@@ -23,4 +20,8 @@ func CreateTestRouter() *gin.Engine {backups_controllers_logical.GetBackupController(),restores.GetRestoreController(),)++ backups_controllers_logical.GetBackupController().RegisterPublicRoutes(router.Group("/api/v1"))++ return router}diff --git a/backend/internal/util/io/counting_writer.go b/backend/internal/util/io/counting_writer.goindex 39e5c00e..cdf4d24d 100644--- a/backend/internal/util/io/counting_writer.go+++ b/backend/internal/util/io/counting_writer.go@@ -1,22 +1,31 @@package io_utils-import "io"+import (+ "io"+ "sync/atomic"+)+// CountingWriter counts atomically because compressing writers hand their output+// to internal goroutines, so the count is read from a different goroutine than+// the one that produced the bytes.type CountingWriter struct {- Writer io.Writer- BytesWritten int64+ writer io.Writer+ bytesWritten atomic.Int64}func NewCountingWriter(writer io.Writer) *CountingWriter {- return &CountingWriter{Writer: writer}+ return &CountingWriter{writer: writer}}func (cw *CountingWriter) Write(p []byte) (n int, err error) {- n, err = cw.Writer.Write(p)- cw.BytesWritten += int64(n)+ n, err = cw.writer.Write(p)+ if n > 0 {+ cw.bytesWritten.Add(int64(n))+ }+return n, err}func (cw *CountingWriter) GetBytesWritten() int64 {- return cw.BytesWritten+ return cw.bytesWritten.Load()}diff --git a/backend/internal/util/io/counting_writer_test.go b/backend/internal/util/io/counting_writer_test.gonew file mode 100644index 00000000..1d61fd7e--- /dev/null+++ b/backend/internal/util/io/counting_writer_test.go@@ -0,0 +1,38 @@+package io_utils++import (+ "io"+ "sync"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func Test_CountingWriter_WhenWrittenFromManyGoroutines_CountsEveryByte(t *testing.T) {+ const writerCount = 16+ const writesPerWriter = 64+ const payloadSize = 128++ countingWriter := NewCountingWriter(io.Discard)+ payload := make([]byte, payloadSize)++ var writers sync.WaitGroup++ for range writerCount {+ writers.Go(func() {+ for range writesPerWriter {+ _, err := countingWriter.Write(payload)+ assert.NoError(t, err)+ }+ })+ }++ writers.Wait()++ require.Equal(+ t,+ int64(writerCount*writesPerWriter*payloadSize),+ countingWriter.GetBytesWritten(),+ )+}