Skip to content

Commit

Permalink
added non-blocking write to channel and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ValyaB committed Oct 22, 2024
1 parent ea139e0 commit b697eef
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
14 changes: 11 additions & 3 deletions internal/monitor/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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)
Expand All @@ -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")
}
}
}

Expand Down
15 changes: 10 additions & 5 deletions internal/monitor/metatada_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down

0 comments on commit b697eef

Please sign in to comment.