~blu/artemis

34176cf1632bd32341ba140789b552133b644105 — Bryant Conquest 1 year, 4 months ago e6e7d81
add pattern parameter for purge endpoint
2 files changed, 22 insertions(+), 15 deletions(-)

M cache/cache.go
M main.go
M cache/cache.go => cache/cache.go +15 -14
@@ 7,6 7,7 @@ import (
	"log"
	"os"
	"path/filepath"
	"regexp"
	"sort"
	"sync"
	"syscall"


@@ 55,18 56,18 @@ func (c *Cache) WithFileClient(fc b2.Actions) *Cache {
	return c
}

func (c Cache) PurgeCache() error {
	files, err := os.ReadDir(c.CacheDirectory)
	if err != nil {
		return err
	}

	for _, f := range files {
		err := os.Remove(filepath.Join(c.CacheDirectory, f.Name()))
		if err != nil {
			log.Println(err)
func (c Cache) PurgeCache(pattern string) error {
	r := regexp.MustCompile(pattern)
	c.Files.Range(func(key any, value any) bool {
		f := value.(CachedAsset)
		if r.MatchString(f.Name) {
			err := os.Remove(filepath.Join(c.CacheDirectory, f.PathHash))
			if err != nil {
				log.Println(err)
			}
		}
	}
		return true
	})

	return nil
}


@@ 96,15 97,15 @@ func (c *Cache) readAsset(hash string) ([]byte, error) {
}

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

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

	toFree := make([]*CachedAsset, 0)
	toFree := make([]CachedAsset, 0)
	toFreeSize := 0
	for _, a := range assets {
		toFree = append(toFree, a)

M main.go => main.go +7 -1
@@ 45,7 45,13 @@ func MetricsHandler() http.Handler {

func Purge(h *Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		err := h.Cache.PurgeCache()
		values := r.URL.Query()
		pattern := ".*"
		if values.Has("pattern") {
			pattern = values.Get("pattern")
		}

		err := h.Cache.PurgeCache(pattern)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return