~blu/artemis

14cce4001c5c82c244561d8f41e45f05fcade05d — Bryant Conquest 1 year, 5 months ago c494c87
move to sync map instead of home rolled implementation
1 files changed, 15 insertions(+), 18 deletions(-)

M cache/cache.go
M cache/cache.go => cache/cache.go +15 -18
@@ 17,8 17,7 @@ import (

type Cache struct {
	CacheDirectory string
	Files          map[string]*CachedAsset
	FileLock       *sync.RWMutex
	Files          *sync.Map

	FileClient b2.Actions
}


@@ 37,8 36,7 @@ var NotEnoughSpace = errors.New("not enough space on disk")
func NewCache() *Cache {
	return &Cache{
		CacheDirectory: ".",
		Files:          make(map[string]*CachedAsset),
		FileLock:       &sync.RWMutex{},
		Files:          &sync.Map{},
	}
}



@@ 76,8 74,12 @@ func (c Cache) PurgeCache() error {
func (c *Cache) LoadOrReadAsset(path string) ([]byte, error, bool) {
	hash := hashPath(path)
	data, err := c.readAsset(hash)
	if err == nil && c.Files[hash].DiesAt.After(time.Now()) {
		return data, err, true
	if err == nil {
		if r, ok := c.Files.Load(hash); ok {
			if (r.(CachedAsset)).DiesAt.After(time.Now()) {
				return data, err, true
			}
		}
	}

	data, err = c.downloadAsset(path)


@@ 95,11 97,10 @@ func (c *Cache) readAsset(hash string) ([]byte, error) {

func (c *Cache) freeCache(toFreeSpace uint64) error {
	assets := make([]*CachedAsset, 0)
	c.FileLock.RLock()
	for _, value := range c.Files {
		assets = append(assets, value)
	}
	c.FileLock.RUnlock()
	c.Files.Range(func(key any, value any) bool {
		assets = append(assets, (value.(*CachedAsset)))
		return true
	})

	sort.Slice(assets, func(i, j int) bool { return assets[i].Hits < assets[j].Hits })



@@ 117,15 118,13 @@ func (c *Cache) freeCache(toFreeSpace uint64) error {
		return NotEnoughSpace
	}

	c.FileLock.Lock()
	for _, a := range toFree {
		log.Println(filepath.Join(c.CacheDirectory, a.PathHash))
		if err := os.Remove(filepath.Join(c.CacheDirectory, a.PathHash)); err != nil {
			log.Println(err)
		}
		delete(c.Files, a.ContentHash)
		c.Files.Delete(a.ContentHash)
	}
	c.FileLock.Unlock()
	return nil
}



@@ 173,16 172,14 @@ func (c Cache) downloadAsset(path string) ([]byte, error) {
		return nil, err
	}

	c.FileLock.Lock()
	c.Files[hashPath(path)] = &CachedAsset{
	c.Files.Store(hashPath(path), CachedAsset{
		Name:        path,
		Size:        len(data),
		Hits:        1,
		PathHash:    hashPath(path),
		ContentHash: HashContent(data),
		DiesAt:      time.Now().Add(1 * time.Hour), // TODO: Configure
	}
	c.FileLock.Unlock()
	})

	return data, nil
}