From 4bcb077fbf0f661fa93f6804908b97444a37b6a3 Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Wed, 2 Mar 2022 21:19:17 +0100 Subject: [PATCH] Use atomic operations to update status Signed-off-by: Knut Ahlers --- main.go | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/main.go b/main.go index 30deb45..3a8a85d 100644 --- a/main.go +++ b/main.go @@ -42,10 +42,11 @@ const ( ) const ( - filenameInput = "input.zip" - filenameStatus = "status.json" - filenameOutputDir = "output" - sleepBase = 1.5 + filenameInput = "input.zip" + filenameStatus = "status.json" + filenameStatusTemp = "status.tmp.json" + filenameOutputDir = "output" + sleepBase = 1.5 ) type jobStatus struct { @@ -79,13 +80,20 @@ func (s *jobStatus) UpdateStatus(st status) { func (s jobStatus) Save() error { uid, _ := uuid.FromString(s.UUID) // #nosec G104 - f, err := os.Create(pathFromUUID(uid, filenameStatus)) + f, err := os.Create(pathFromUUID(uid, filenameStatusTemp)) if err != nil { return err } defer f.Close() - return json.NewEncoder(f).Encode(s) + if err = json.NewEncoder(f).Encode(s); err != nil { + return err + } + + return os.Rename( + pathFromUUID(uid, filenameStatusTemp), + pathFromUUID(uid, filenameStatus), + ) } func urlMust(u *url.URL, err error) *url.URL {