mirror of
https://github.com/ddworken/hishtory.git
synced 2025-06-25 14:32:14 +02:00
Automatic retries when the DB is busy
This commit is contained in:
parent
c918c5042e
commit
30ee41a6ea
@ -8,6 +8,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"log"
|
"log"
|
||||||
|
"math/rand"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
@ -820,3 +821,31 @@ func ApiPost(path, contentType string, data []byte) ([]byte, error) {
|
|||||||
func IsOfflineError(err error) bool {
|
func IsOfflineError(err error) bool {
|
||||||
return strings.Contains(err.Error(), "dial tcp: lookup api.hishtory.dev") || strings.Contains(err.Error(), "read: connection reset by peer")
|
return strings.Contains(err.Error(), "dial tcp: lookup api.hishtory.dev") || strings.Contains(err.Error(), "read: connection reset by peer")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ReliableDbCreate(db *gorm.DB, entry interface{}) error {
|
||||||
|
var err error = nil
|
||||||
|
i := 0
|
||||||
|
for i = 0; i < 10; i++ {
|
||||||
|
result := db.Create(entry)
|
||||||
|
err = result.Error
|
||||||
|
if err != nil {
|
||||||
|
errMsg := err.Error()
|
||||||
|
if errMsg == "database is locked (5) (SQLITE_BUSY)" || errMsg == "database is locked (261)" {
|
||||||
|
time.Sleep(time.Duration(i*rand.Intn(100)) * time.Millisecond)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.Contains(errMsg, "constraint failed: UNIQUE constraint failed") {
|
||||||
|
if i == 0 {
|
||||||
|
return err
|
||||||
|
} else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err != nil && err.Error() != "database is locked (5) (SQLITE_BUSY)" {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fmt.Errorf("failed to create DB entry even with %d retries: %v", i, err)
|
||||||
|
}
|
||||||
|
@ -152,9 +152,8 @@ func saveHistoryEntry() {
|
|||||||
// Persist it locally
|
// Persist it locally
|
||||||
db, err := lib.OpenLocalSqliteDb()
|
db, err := lib.OpenLocalSqliteDb()
|
||||||
lib.CheckFatalError(err)
|
lib.CheckFatalError(err)
|
||||||
result := db.Create(entry)
|
err = lib.ReliableDbCreate(db, entry)
|
||||||
lib.CheckFatalError(result.Error)
|
lib.CheckFatalError(err)
|
||||||
// TODO: ^ sometimes fails with the error "database is locked (261)". Fix this by retrying.
|
|
||||||
|
|
||||||
// Persist it remotely
|
// Persist it remotely
|
||||||
encEntry, err := data.EncryptHistoryEntry(config.UserSecret, *entry)
|
encEntry, err := data.EncryptHistoryEntry(config.UserSecret, *entry)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user