Fix: immediately update provider when modtime too old

This commit is contained in:
Dreamacro 2022-12-31 16:30:29 +08:00
parent fbca37c42b
commit 2301b909d2
1 changed files with 32 additions and 20 deletions

View File

@ -21,6 +21,7 @@ type parser = func([]byte) (any, error)
type fetcher struct { type fetcher struct {
name string name string
vehicle types.Vehicle vehicle types.Vehicle
interval time.Duration
updatedAt *time.Time updatedAt *time.Time
ticker *time.Ticker ticker *time.Ticker
done chan struct{} done chan struct{}
@ -39,15 +40,17 @@ func (f *fetcher) VehicleType() types.VehicleType {
func (f *fetcher) Initial() (any, error) { func (f *fetcher) Initial() (any, error) {
var ( var (
buf []byte buf []byte
err error err error
isLocal bool isLocal bool
immediatelyUpdate bool
) )
if stat, fErr := os.Stat(f.vehicle.Path()); fErr == nil { if stat, fErr := os.Stat(f.vehicle.Path()); fErr == nil {
buf, err = os.ReadFile(f.vehicle.Path()) buf, err = os.ReadFile(f.vehicle.Path())
modTime := stat.ModTime() modTime := stat.ModTime()
f.updatedAt = &modTime f.updatedAt = &modTime
isLocal = true isLocal = true
immediatelyUpdate = time.Since(modTime) > f.interval
} else { } else {
buf, err = f.vehicle.Read() buf, err = f.vehicle.Read()
} }
@ -86,7 +89,7 @@ func (f *fetcher) Initial() (any, error) {
// pull proxies automatically // pull proxies automatically
if f.ticker != nil { if f.ticker != nil {
go f.pullLoop() go f.pullLoop(immediatelyUpdate)
} }
return proxies, nil return proxies, nil
@ -130,25 +133,33 @@ func (f *fetcher) Destroy() error {
return nil return nil
} }
func (f *fetcher) pullLoop() { func (f *fetcher) pullLoop(immediately bool) {
update := func() {
elm, same, err := f.Update()
if err != nil {
log.Warnln("[Provider] %s pull error: %s", f.Name(), err.Error())
return
}
if same {
log.Debugln("[Provider] %s's proxies doesn't change", f.Name())
return
}
log.Infoln("[Provider] %s's proxies update", f.Name())
if f.onUpdate != nil {
f.onUpdate(elm)
}
}
if immediately {
update()
}
for { for {
select { select {
case <-f.ticker.C: case <-f.ticker.C:
elm, same, err := f.Update() update()
if err != nil {
log.Warnln("[Provider] %s pull error: %s", f.Name(), err.Error())
continue
}
if same {
log.Debugln("[Provider] %s's proxies doesn't change", f.Name())
continue
}
log.Infoln("[Provider] %s's proxies update", f.Name())
if f.onUpdate != nil {
f.onUpdate(elm)
}
case <-f.done: case <-f.done:
f.ticker.Stop() f.ticker.Stop()
return return
@ -178,6 +189,7 @@ func newFetcher(name string, interval time.Duration, vehicle types.Vehicle, pars
name: name, name: name,
ticker: ticker, ticker: ticker,
vehicle: vehicle, vehicle: vehicle,
interval: interval,
parser: parser, parser: parser,
done: make(chan struct{}, 1), done: make(chan struct{}, 1),
onUpdate: onUpdate, onUpdate: onUpdate,