Add retry for bbolt open

This commit is contained in:
世界 2023-10-16 12:00:00 +08:00
parent 2371f0fd51
commit e5d191ca73
No known key found for this signature in database
GPG key ID: CD109927C34A63C4

View file

@ -1,6 +1,7 @@
package cachefile package cachefile
import ( import (
"errors"
"net/netip" "net/netip"
"os" "os"
"strings" "strings"
@ -11,6 +12,7 @@ import (
bboltErrors "github.com/sagernet/bbolt/errors" bboltErrors "github.com/sagernet/bbolt/errors"
"github.com/sagernet/sing-box/adapter" "github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing/common" "github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
) )
var ( var (
@ -42,13 +44,25 @@ type CacheFile struct {
func Open(path string, cacheID string) (*CacheFile, error) { func Open(path string, cacheID string) (*CacheFile, error) {
const fileMode = 0o666 const fileMode = 0o666
options := bbolt.Options{Timeout: time.Second} options := bbolt.Options{Timeout: time.Second}
db, err := bbolt.Open(path, fileMode, &options) var (
switch err { db *bbolt.DB
case bboltErrors.ErrInvalid, bboltErrors.ErrChecksum, bboltErrors.ErrVersionMismatch: err error
if err = os.Remove(path); err != nil { )
for i := 0; i < 10; i++ {
db, err = bbolt.Open(path, fileMode, &options)
if err == nil {
break break
} }
db, err = bbolt.Open(path, 0o666, &options) if errors.Is(err, bboltErrors.ErrTimeout) {
continue
}
if E.IsMulti(err, bboltErrors.ErrInvalid, bboltErrors.ErrChecksum, bboltErrors.ErrVersionMismatch) {
rmErr := os.Remove(path)
if rmErr != nil {
return nil, err
}
}
time.Sleep(100 * time.Millisecond)
} }
if err != nil { if err != nil {
return nil, err return nil, err