github.com/matrixorigin/matrixone@v0.7.0/pkg/fileservice/mem_cache.go (about) 1 // Copyright 2022 Matrix Origin 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package fileservice 16 17 import ( 18 "context" 19 "sync/atomic" 20 21 "github.com/matrixorigin/matrixone/pkg/util/trace" 22 ) 23 24 type MemCache struct { 25 lru *LRU 26 stats *CacheStats 27 } 28 29 func NewMemCache(capacity int64) *MemCache { 30 return &MemCache{ 31 lru: NewLRU(capacity), 32 stats: new(CacheStats), 33 } 34 } 35 36 var _ Cache = new(MemCache) 37 38 func (m *MemCache) Read( 39 ctx context.Context, 40 vector *IOVector, 41 ) ( 42 err error, 43 ) { 44 _, span := trace.Start(ctx, "MemCache.Read") 45 defer span.End() 46 47 numHit := 0 48 defer func() { 49 if m.stats != nil { 50 atomic.AddInt64(&m.stats.NumRead, int64(len(vector.Entries))) 51 atomic.AddInt64(&m.stats.NumHit, int64(numHit)) 52 } 53 }() 54 55 for i, entry := range vector.Entries { 56 if entry.done { 57 continue 58 } 59 if entry.ToObject == nil { 60 continue 61 } 62 key := CacheKey{ 63 Path: vector.FilePath, 64 Offset: entry.Offset, 65 Size: entry.Size, 66 } 67 obj, size, ok := m.lru.Get(key) 68 if ok { 69 vector.Entries[i].Object = obj 70 vector.Entries[i].ObjectSize = size 71 vector.Entries[i].done = true 72 numHit++ 73 } 74 } 75 76 return 77 } 78 79 func (m *MemCache) Update( 80 ctx context.Context, 81 vector *IOVector, 82 ) error { 83 for _, entry := range vector.Entries { 84 if entry.Object == nil { 85 continue 86 } 87 key := CacheKey{ 88 Path: vector.FilePath, 89 Offset: entry.Offset, 90 Size: entry.Size, 91 } 92 m.lru.Set(key, entry.Object, entry.ObjectSize) 93 } 94 return nil 95 } 96 97 func (m *MemCache) Flush() { 98 m.lru.Flush() 99 } 100 101 func (m *MemCache) CacheStats() *CacheStats { 102 return m.stats 103 }