diff --git a/internal/monitor/metadata.go b/internal/monitor/metadata.go index eda619c7..1888c272 100644 --- a/internal/monitor/metadata.go +++ b/internal/monitor/metadata.go @@ -30,12 +30,16 @@ func (m *Metadata) Save(file string) error { return os.WriteFile(file, contents, 0o600) } +var errEmptyMetadata = fmt.Errorf("metadata file is empty") + func (m *Metadata) Load(file string) error { contents, err := os.ReadFile(file) if err != nil { return fmt.Errorf("reading file: %w", err) } - + if len(contents) == 0 { + return errEmptyMetadata + } if err := json.Unmarshal(contents, m); err != nil { return fmt.Errorf("file: %v content: %v parsing json: %w", file, string(contents), err) } @@ -48,7 +52,7 @@ func watchForMetadataChanges(ctx context.Context, log logrus.FieldLogger, metada if err != nil { return nil, fmt.Errorf("setting up new watcher: %w", err) } - updates := make(chan Metadata, 10) + updates := make(chan Metadata, 1) if err := watcher.Add(filepath.Dir(metadataFilePath)); err != nil { return nil, fmt.Errorf("adding watch: %w", err) @@ -61,7 +65,11 @@ func watchForMetadataChanges(ctx context.Context, log logrus.FieldLogger, metada log.Warnf("loading metadata failed: %v", err) } } else { - updates <- metadata + select { + case updates <- metadata: + default: + log.Warnf("metadata update skipped, channel full") + } } } diff --git a/internal/monitor/metatada_test.go b/internal/monitor/metatada_test.go index e5237ca2..07bacaa6 100644 --- a/internal/monitor/metatada_test.go +++ b/internal/monitor/metatada_test.go @@ -73,15 +73,20 @@ func Test_monitor_waitForMetadata(t *testing.T) { time.Sleep(time.Second * 1) // create the file, expect the event to arrive at updates channel - meta := Metadata{ - ClusterID: uuid.New().String(), - LastStart: 123, + var meta Metadata + maxI := int64(124) + for i := int64(0); i <= maxI; i++ { + meta = Metadata{ + ClusterID: uuid.New().String(), + LastStart: i, + } + require.NoError(t, meta.Save(syncFile)) } - require.NoError(t, meta.Save(syncFile)) metadata, ok := <-updates require.True(t, ok) - require.Equal(t, int64(123), metadata.LastStart) + require.True(t, maxI >= metadata.LastStart, "expected last start to be %d, got %d", maxI, metadata.LastStart) + require.True(t, metadata.LastStart != 0, "expected last start to be non-zero, got %d", metadata.LastStart) cancel()