1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
15 var DefaultBlockCache = &BlockCache{}
17 type BlockCache struct {
18 // Maximum number of blocks to keep in the cache. If 0, a
19 // default size (currently 4) is used instead.
22 cache map[string]*cacheBlock
27 const defaultMaxBlocks = 4
29 // Sweep deletes the least recently used blocks from the cache until
30 // there are no more than MaxBlocks left.
31 func (c *BlockCache) Sweep() {
33 if max < defaultMaxBlocks {
34 max = defaultMaxBlocks
38 if len(c.cache) <= max {
41 lru := make([]time.Time, 0, len(c.cache))
42 for _, b := range c.cache {
43 lru = append(lru, b.lastUse)
45 sort.Sort(sort.Reverse(timeSlice(lru)))
47 for loc, b := range c.cache {
48 if !b.lastUse.After(threshold) {
54 // Get returns data from the cache, first retrieving it from Keep if
56 func (c *BlockCache) Get(kc *KeepClient, locator string) ([]byte, error) {
57 c.setupOnce.Do(c.setup)
58 cacheKey := locator[:32]
60 b, ok := c.cache[cacheKey]
61 if !ok || b.err != nil {
63 fetched: make(chan struct{}),
68 rdr, _, _, err := kc.Get(locator)
69 data := bytes.NewBuffer(make([]byte, 0, BLOCKSIZE))
71 _, err = io.Copy(data, rdr)
78 b.data, b.err = data.Bytes(), err
86 // Wait (with mtx unlocked) for the fetch goroutine to finish,
87 // in case it hasn't already.
91 b.lastUse = time.Now()
96 func (c *BlockCache) setup() {
97 c.cache = make(map[string]*cacheBlock)
100 func (c *BlockCache) Clear() {
106 type timeSlice []time.Time
108 func (ts timeSlice) Len() int { return len(ts) }
110 func (ts timeSlice) Less(i, j int) bool { return ts[i].Before(ts[j]) }
112 func (ts timeSlice) Swap(i, j int) { ts[i], ts[j] = ts[j], ts[i] }
114 type cacheBlock struct {
117 fetched chan struct{}