Skip to content

Commit

Permalink
filecache: use rename for an atomic write (#1816)
Browse files Browse the repository at this point in the history
Signed-off-by: Val Packett <[email protected]>
  • Loading branch information
valpackett authored Oct 25, 2023
1 parent 99c057b commit 6e61e20
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions internal/filecache/file_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,28 @@ func (fc *fileCache) Add(key Key, content io.Reader) (err error) {
fc.mux.Lock()
defer fc.mux.Unlock()

file, err := os.Create(fc.path(key))
// Use rename for an atomic write
path := fc.path(key)
file, err := os.Create(path + ".tmp")
if err != nil {
return
}
defer func() {
if err != nil {
_ = os.Remove(file.Name())
}
}()
defer file.Close()
_, err = io.Copy(file, content)
if _, err = io.Copy(file, content); err != nil {
return
}
if err = file.Sync(); err != nil {
return
}
if err = file.Close(); err != nil {
return
}
err = os.Rename(file.Name(), path)
return
}

Expand Down

0 comments on commit 6e61e20

Please sign in to comment.