2
2
mirror of https://github.com/octoleo/restic.git synced 2024-06-22 10:34:51 +00:00

cache: Simplify loadFromCacheOrDelegate

This commit is contained in:
Michael Eischer 2021-09-20 22:08:05 +02:00
parent 5c6b6edefe
commit aa3b1925b4

View File

@ -131,21 +131,19 @@ func (b *Backend) cacheFile(ctx context.Context, h restic.Handle) error {
return nil return nil
} }
// loadFromCacheOrDelegate will try to load the file from the cache, and fall // loadFromCache will try to load the file from the cache.
// back to the backend if that fails. func (b *Backend) loadFromCache(ctx context.Context, h restic.Handle, length int, offset int64, consumer func(rd io.Reader) error) (bool, error) {
func (b *Backend) loadFromCacheOrDelegate(ctx context.Context, h restic.Handle, length int, offset int64, consumer func(rd io.Reader) error) error {
rd, err := b.Cache.load(h, length, offset) rd, err := b.Cache.load(h, length, offset)
if err != nil { if err != nil {
debug.Log("error caching %v: %v, falling back to backend", h, err) return false, err
return b.Backend.Load(ctx, h, length, offset, consumer)
} }
err = consumer(rd) err = consumer(rd)
if err != nil { if err != nil {
_ = rd.Close() // ignore secondary errors _ = rd.Close() // ignore secondary errors
return err return true, err
} }
return rd.Close() return true, rd.Close()
} }
// Load loads a file from the cache or the backend. // Load loads a file from the cache or the backend.
@ -161,15 +159,10 @@ func (b *Backend) Load(ctx context.Context, h restic.Handle, length int, offset
} }
// try loading from cache without checking that the handle is actually cached // try loading from cache without checking that the handle is actually cached
rd, err := b.Cache.load(h, length, offset) inCache, err := b.loadFromCache(ctx, h, length, offset, consumer)
if err == nil { if inCache {
err = consumer(rd)
if err != nil {
_ = rd.Close() // ignore secondary errors
return err return err
} }
return rd.Close()
}
debug.Log("error loading %v from cache: %v", h, err) debug.Log("error loading %v from cache: %v", h, err)
// if we don't automatically cache this file type, fall back to the backend // if we don't automatically cache this file type, fall back to the backend
@ -181,7 +174,10 @@ func (b *Backend) Load(ctx context.Context, h restic.Handle, length int, offset
debug.Log("auto-store %v in the cache", h) debug.Log("auto-store %v in the cache", h)
err = b.cacheFile(ctx, h) err = b.cacheFile(ctx, h)
if err == nil { if err == nil {
return b.loadFromCacheOrDelegate(ctx, h, length, offset, consumer) inCache, err = b.loadFromCache(ctx, h, length, offset, consumer)
if inCache {
return err
}
} }
debug.Log("error caching %v: %v, falling back to backend", h, err) debug.Log("error caching %v: %v, falling back to backend", h, err)