chore: force refresh provider in background

This commit is contained in:
wwqgtxx
2024-09-22 00:24:49 +08:00
parent 7dafe7889e
commit 223eae0e06
4 changed files with 17 additions and 22 deletions

View File

@@ -65,8 +65,7 @@ func (f *Fetcher[V]) Initial() (V, error) {
modTime := stat.ModTime()
f.updatedAt = modTime
isLocal = true
if f.interval != 0 && modTime.Add(f.interval).Before(time.Now()) {
log.Warnln("[Provider] %s not updated for a long time, force refresh", f.Name())
if time.Since(modTime) > f.interval {
forceUpdate = true
}
} else {
@@ -78,21 +77,7 @@ func (f *Fetcher[V]) Initial() (V, error) {
return lo.Empty[V](), err
}
var contents V
if forceUpdate {
var forceBuf []byte
if forceBuf, err = f.vehicle.Read(f.ctx); err == nil {
if contents, err = f.parser(forceBuf); err == nil {
isLocal = false
buf = forceBuf
}
}
}
if err != nil || !forceUpdate {
contents, err = f.parser(buf)
}
contents, err := f.parser(buf)
if err != nil {
if !isLocal {
return lo.Empty[V](), err
@@ -135,7 +120,7 @@ func (f *Fetcher[V]) Initial() (V, error) {
return lo.Empty[V](), err
}
} else if f.interval > 0 {
go f.pullLoop()
go f.pullLoop(forceUpdate)
}
return contents, nil
@@ -164,7 +149,7 @@ func (f *Fetcher[V]) SideUpdate(buf []byte) (V, bool, error) {
}
if f.vehicle.Type() != types.File {
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
if err = safeWrite(f.vehicle.Path(), buf); err != nil {
return lo.Empty[V](), false, err
}
}
@@ -183,12 +168,17 @@ func (f *Fetcher[V]) Close() error {
return nil
}
func (f *Fetcher[V]) pullLoop() {
func (f *Fetcher[V]) pullLoop(forceUpdate bool) {
initialInterval := f.interval - time.Since(f.updatedAt)
if initialInterval > f.interval {
initialInterval = f.interval
}
if forceUpdate {
log.Warnln("[Provider] %s not updated for a long time, force refresh", f.Name())
f.update(f.vehicle.Path())
}
timer := time.NewTimer(initialInterval)
defer timer.Stop()
for {

View File

@@ -24,6 +24,10 @@ func (f *FileVehicle) Path() string {
return f.path
}
func (f *FileVehicle) Url() string {
return "file://" + f.path
}
func (f *FileVehicle) Read(ctx context.Context) ([]byte, error) {
return os.ReadFile(f.path)
}