Skip to content

Commit

Permalink
[feature] Compress backup file
Browse files Browse the repository at this point in the history
  • Loading branch information
g3force committed May 30, 2019
1 parent 708ee56 commit cd6bc02
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ yarn-error.log*
# app-specific ignores
history.json
gc-state.json
gc-state.backup
gc-state.backup.gz
23 changes: 19 additions & 4 deletions internal/app/controller/engineHistory.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package controller

import (
"bufio"
"compress/gzip"
"encoding/json"
"github.com/pkg/errors"
"io/ioutil"
Expand All @@ -12,7 +14,7 @@ import (

const maxHistorySize = 10
const stateFilename = "gc-state.json"
const backupFilename = "gc-state.backup"
const backupFilename = "gc-state.backup.gz"

type PersistentState struct {
CurrentState *GameControllerState `json:"currentState"`
Expand Down Expand Up @@ -70,8 +72,10 @@ func (s *PersistentState) RevertProtocolEntry(id string) error {
}

type StatePreserver struct {
file *os.File
backupFile *os.File
file *os.File
backupFile *os.File
backupWriter *bufio.Writer
backupWriterGzip *gzip.Writer
}

// Open opens the state and backup file
Expand All @@ -87,6 +91,8 @@ func (r *StatePreserver) Open() error {
return err
}
r.backupFile = f
r.backupWriterGzip = gzip.NewWriter(r.backupFile)
r.backupWriter = bufio.NewWriter(r.backupWriterGzip)
return nil
}

Expand All @@ -110,6 +116,12 @@ func (r *StatePreserver) Close() {
}
}
if r.backupFile != nil {
if err := r.backupWriter.Flush(); err != nil {
log.Print("Could not flush backup writer: ", err)
}
if err := r.backupWriterGzip.Close(); err != nil {
log.Print("Could not close backup writer: ", err)
}
if err := r.backupFile.Close(); err != nil {
log.Print("Could not close backup file", err)
}
Expand Down Expand Up @@ -160,8 +172,11 @@ func (r *StatePreserver) Save(state *PersistentState) {
return
}
jsonCompact = append(jsonCompact, []byte("\n")...)
_, err = r.backupFile.Write(jsonCompact)
_, err = r.backupWriter.Write(jsonCompact)
if err != nil {
log.Print("Could not write to backup file: ", err)
}
if err := r.backupWriter.Flush(); err != nil {
log.Print("Could not flush backup writer: ", err)
}
}

0 comments on commit cd6bc02

Please sign in to comment.