Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 13 additions & 32 deletions pkg/apk/apk/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@ func (f *flightCache[K, V]) Forget(key K) {
}

type Cache struct {
etagCache *sync.Map
headFlight *singleflight.Group
getFlight *singleflight.Group

discoverKeys *flightCache[string, []Key]
etags *flightCache[string, *http.Response]
}

// NewCache returns a new Cache, which allows us to persist the results of HEAD requests
Expand All @@ -109,33 +109,13 @@ func NewCache(etag bool) *Cache {
}

if etag {
c.etagCache = &sync.Map{}
//nolint:bodyclose // Body is already closed before caching.
c.etags = newFlightCache[string, *http.Response]()
}

return c
}

func (c *Cache) load(cacheFile string) (*http.Response, bool) {
if c == nil || c.etagCache == nil {
return nil, false
}

v, ok := c.etagCache.Load(cacheFile)
if !ok {
return nil, false
}

return v.(*http.Response), true
}

func (c *Cache) store(cacheFile string, resp *http.Response) {
if c == nil || c.etagCache == nil {
return
}

c.etagCache.Store(cacheFile, resp)
}

// cache
type cache struct {
dir string
Expand Down Expand Up @@ -205,12 +185,7 @@ func (t *cacheTransport) RoundTrip(request *http.Request) (*http.Response, error
}

func (t *cacheTransport) head(request *http.Request, cacheFile string) (*http.Response, error) {
resp, ok := t.cache.load(cacheFile)
if ok {
return resp, nil
}

v, err, _ := t.cache.headFlight.Do(cacheFile, func() (any, error) {
fetch := func() (*http.Response, error) {
req := request.Clone(request.Context())
req.Method = http.MethodHead
resp, err := t.wrapped.Do(req)
Expand All @@ -221,14 +196,20 @@ func (t *cacheTransport) head(request *http.Request, cacheFile string) (*http.Re
// HEAD shouldn't have a body. Make sure we close it so we can reuse the connection.
defer resp.Body.Close()

t.cache.store(cacheFile, resp)

return resp, nil
}

v, err, _ := t.cache.headFlight.Do(cacheFile, func() (any, error) {
if t.cache.etags != nil {
//nolint:bodyclose // Body is already closed in fetch.
return t.cache.etags.Do(cacheFile, fetch)
}
//nolint:bodyclose // Body is already closed in fetch.
return fetch()
})
if err != nil {
return nil, err
}

return v.(*http.Response), nil
}

Expand Down
Loading