8000 Keep concurrently appended sources when reloading by wissaaamm · Pull Request #458 · go-ini/ini · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 16 additions & 8 deletions file.go
Original file line number Diff line number Diff line change
Expand Up @@ -418,15 +418,23 @@ func (f *File) loadSource(s dataSource) error {
// *Section and *Key values, so pointers to them see the new contents. On
// error the file is unchanged.
func (f *File) Reload() error {
f.maybeRLock()
sources := f.dataSources
f.maybeRUnlock()
next := &File{options: f.options, byName: make(map[string][]*Section)}
if err := next.load(sources); err != nil {
return err
}
var next *File
for {
f.maybeRLock()
sources := f.dataSources
f.maybeRUnlock()
next = &File{options: f.options, byName: make(map[string][]*Section)}
if err := next.load(sources); err != nil {
return err
}

f.maybeLock()
f.maybeLock()
if len(sources) == len(f.dataSources) {
break
}
// Append added sources while we were loading. Retry with the full list.
f.maybeUnlock()
}
defer f.maybeUnlock()
for name, secs := range next.byName {
old := f.byName[name]
Expand Down
54 changes: 54 additions & 0 deletions reload_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package ini

import (
"sync"
"testing"
)

type blockingReloadSource struct {
dataSource
once sync.Once
started chan struct{}
resume chan struct{}
}

func (s *blockingReloadSource) read() (string, error) {
s.once.Do(func() {
close(s.started)
<-s.resume
})
return s.dataSource.read()
}

func TestFile_ReloadKeepsConcurrentAppend(t *testing.T) {
f, err := Load([]byte("base = original\n"))
if err != nil {
t.Fatal(err)
}
source := &blockingReloadSource{
dataSource: f.dataSources[0],
started: make(chan struct{}),
resume: make(chan struct{}),
}
f.dataSources[0] = source

reloaded := make(chan error, 1)
go func() { reloaded <- f.Reload() }()
<-source.started

// Reload has captured its source list. Append before letting it continue.
err = f.Append([]byte("base = updated\nextra = present\n"))
close(source.resume)
if err != nil {
t.Fatal(err)
}
if err := <-reloaded; err != nil {
t.Fatal(err)
}
if got := f.Section("").Key("base").String(); got != "updated" {
t.Errorf("base = %q, want updated", got)
}
if got := f.Section("").Key("extra").String(); got != "present" {
t.Errorf("extra = %q, want present", got)
}
}
0