github.com/attic-labs/noms@v0.0.0-20210827224422-e5fa29d95e8b/go/nbs/cache.go (about) 1 // Copyright 2016 Attic Labs, Inc. All rights reserved. 2 // Licensed under the Apache License, version 2.0: 3 // http://www.apache.org/licenses/LICENSE-2.0 4 5 package nbs 6 7 import ( 8 "io/ioutil" 9 "os" 10 11 "github.com/attic-labs/noms/go/chunks" 12 "github.com/attic-labs/noms/go/d" 13 "github.com/attic-labs/noms/go/hash" 14 ) 15 16 const ( 17 defaultCacheMemTableSize uint64 = 1 << 27 // 128MiB 18 ) 19 20 func NewCache() *NomsBlockCache { 21 dir, err := ioutil.TempDir("", "") 22 d.PanicIfError(err) 23 store := NewLocalStore(dir, defaultCacheMemTableSize) 24 d.Chk.NoError(err, "opening put cache in %s", dir) 25 return &NomsBlockCache{store, dir} 26 } 27 28 // NomsBlockCache holds Chunks, allowing them to be retrieved by hash or enumerated in hash order. 29 type NomsBlockCache struct { 30 chunks *NomsBlockStore 31 dbDir string 32 } 33 34 // Insert stores c in the cache. 35 func (nbc *NomsBlockCache) Insert(c chunks.Chunk) { 36 d.PanicIfFalse(nbc.chunks.addChunk(addr(c.Hash()), c.Data())) 37 } 38 39 // Has checks if the chunk referenced by hash is in the cache. 40 func (nbc *NomsBlockCache) Has(hash hash.Hash) bool { 41 return nbc.chunks.Has(hash) 42 } 43 44 // HasMany returns a set containing the members of hashes present in the 45 // cache. 46 func (nbc *NomsBlockCache) HasMany(hashes hash.HashSet) hash.HashSet { 47 return nbc.chunks.HasMany(hashes) 48 } 49 50 // Get retrieves the chunk referenced by hash. If the chunk is not present, 51 // Get returns the empty Chunk. 52 func (nbc *NomsBlockCache) Get(hash hash.Hash) chunks.Chunk { 53 return nbc.chunks.Get(hash) 54 } 55 56 // GetMany gets the Chunks with |hashes| from the store. On return, 57 // |foundChunks| will have been fully sent all chunks which have been 58 // found. Any non-present chunks will silently be ignored. 59 func (nbc *NomsBlockCache) GetMany(hashes hash.HashSet, foundChunks chan *chunks.Chunk) { 60 nbc.chunks.GetMany(hashes, foundChunks) 61 } 62 63 // ExtractChunks writes the entire contents of the cache to chunkChan. The 64 // chunks are extracted in insertion order. 65 func (nbc *NomsBlockCache) ExtractChunks(chunkChan chan *chunks.Chunk) { 66 nbc.chunks.extractChunks(chunkChan) 67 } 68 69 // Count returns the number of items in the cache. 70 func (nbc *NomsBlockCache) Count() uint32 { 71 return nbc.chunks.Count() 72 } 73 74 // Destroy drops the cache and deletes any backing storage. 75 func (nbc *NomsBlockCache) Destroy() error { 76 d.Chk.NoError(nbc.chunks.Close()) 77 return os.RemoveAll(nbc.dbDir) 78 }