Skip to content

Commit

Permalink
Fix accidental concurrent preference writes
Browse files Browse the repository at this point in the history
  • Loading branch information
andydotxyz committed Sep 8, 2021
1 parent cf92185 commit b33a8f0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 11 deletions.
22 changes: 11 additions & 11 deletions app/preferences.go
Expand Up @@ -5,7 +5,6 @@ import (
"os"
"path/filepath"
"sync"
"time"

"fyne.io/fyne/v2"
"fyne.io/fyne/v2/internal"
Expand All @@ -23,15 +22,6 @@ type preferences struct {
// Declare conformity with Preferences interface
var _ fyne.Preferences = (*preferences)(nil)

func (p *preferences) resetIgnore() {
go func() {
time.Sleep(time.Millisecond * 100) // writes are not always atomic. 10ms worked, 100 is safer.
p.prefLock.Lock()
p.ignoreChange = false
p.prefLock.Unlock()
}()
}

func (p *preferences) save() error {
return p.saveToFile(p.storagePath())
}
Expand All @@ -40,7 +30,11 @@ func (p *preferences) saveToFile(path string) error {
p.prefLock.Lock()
p.ignoreChange = true
p.prefLock.Unlock()
defer p.resetIgnore()
defer func() {
p.prefLock.Lock()
p.ignoreChange = false
p.prefLock.Unlock()
}()
err := os.MkdirAll(filepath.Dir(path), 0700)
if err != nil { // this is not an exists error according to docs
return err
Expand All @@ -56,11 +50,17 @@ func (p *preferences) saveToFile(path string) error {
return err
}
}
defer file.Close()
encode := json.NewEncoder(file)

p.InMemoryPreferences.ReadValues(func(values map[string]interface{}) {
err = encode.Encode(&values)
})

err2 := file.Sync()
if err == nil {
err = err2
}
return err
}

Expand Down
20 changes: 20 additions & 0 deletions app/preferences_test.go
Expand Up @@ -40,6 +40,26 @@ func TestPreferences_Save(t *testing.T) {
assert.JSONEq(t, string(expected), string(content))
}

func TestPreferences_Save_OverwriteFast(t *testing.T) {
p := loadPreferences("dummy")
p.WriteValues(func(val map[string]interface{}) {
val["key"] = "value"
})

path := filepath.Join(os.TempDir(), "fynePrefs2.json")
defer os.Remove(path)
p.saveToFile(path)

p.WriteValues(func(val map[string]interface{}) {
val["key2"] = "value2"
})
p.saveToFile(path)

p2 := loadPreferences("dummy")
p2.loadFromFile(path)
assert.Equal(t, "value2", p2.String("key2"))
}

func TestPreferences_Load(t *testing.T) {
p := loadPreferences("dummy")
p.loadFromFile(filepath.Join("testdata", "preferences.json"))
Expand Down

0 comments on commit b33a8f0

Please sign in to comment.