1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
16 var DefaultBlockCache = &BlockCache{}
18 type BlockCache struct {
19 // Maximum number of blocks to keep in the cache. If 0, a
20 // default size (currently 4) is used instead.
23 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() {
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 // ReadAt returns data from the cache, first retrieving it from Keep if
56 func (c *BlockCache) ReadAt(kc *KeepClient, locator string, p []byte, off int) (int, error) {
57 buf, err := c.Get(kc, locator)
62 return 0, io.ErrUnexpectedEOF
64 return copy(p, buf[off:]), nil
67 // Get returns data from the cache, first retrieving it from Keep if
69 func (c *BlockCache) Get(kc *KeepClient, locator string) ([]byte, error) {
70 cacheKey := locator[:32]
72 if parts := strings.SplitN(locator, "+", 3); len(parts) >= 2 {
73 datasize, err := strconv.ParseInt(parts[1], 10, 32)
74 if err == nil && datasize >= 0 {
75 bufsize = int(datasize)
80 c.cache = make(map[string]*cacheBlock)
82 b, ok := c.cache[cacheKey]
83 if !ok || b.err != nil {
85 fetched: make(chan struct{}),
90 rdr, size, _, err := kc.Get(locator)
93 data = make([]byte, size, bufsize)
94 _, err = io.ReadFull(rdr, data)
101 b.data, b.err = data, err
109 // Wait (with mtx unlocked) for the fetch goroutine to finish,
110 // in case it hasn't already.
114 b.lastUse = time.Now()
119 func (c *BlockCache) Clear() {
125 type timeSlice []time.Time
127 func (ts timeSlice) Len() int { return len(ts) }
129 func (ts timeSlice) Less(i, j int) bool { return ts[i].Before(ts[j]) }
131 func (ts timeSlice) Swap(i, j int) { ts[i], ts[j] = ts[j], ts[i] }
133 type cacheBlock struct {
136 fetched chan struct{}