garm/cache/instance_cache.go
Gabriel Adrian Samfira 1a719567ff Add rate limit cache and fixes
This change adds a loop that keeps a cache of credentials rate limits
as reported by the github API. The cache is updated every 30 seconds
and is purely informational for the user.

This change also adds some caching improvements. Functions that return
values from the cache as lists, will now sort by ID or creation date.

Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
2025-05-08 21:39:55 +00:00

110 lines
2.3 KiB
Go

package cache
import (
"sync"
"github.com/cloudbase/garm/params"
)
var instanceCache *InstanceCache
func init() {
cache := &InstanceCache{
cache: make(map[string]params.Instance),
}
instanceCache = cache
}
type InstanceCache struct {
mux sync.Mutex
cache map[string]params.Instance
}
func (i *InstanceCache) SetInstance(instance params.Instance) {
i.mux.Lock()
defer i.mux.Unlock()
i.cache[instance.Name] = instance
}
func (i *InstanceCache) GetInstance(name string) (params.Instance, bool) {
i.mux.Lock()
defer i.mux.Unlock()
if instance, ok := i.cache[name]; ok {
return instance, true
}
return params.Instance{}, false
}
func (i *InstanceCache) DeleteInstance(name string) {
i.mux.Lock()
defer i.mux.Unlock()
delete(i.cache, name)
}
func (i *InstanceCache) GetAllInstances() []params.Instance {
i.mux.Lock()
defer i.mux.Unlock()
instances := make([]params.Instance, 0, len(i.cache))
for _, instance := range i.cache {
instances = append(instances, instance)
}
sortByCreationDate(instances)
return instances
}
func (i *InstanceCache) GetInstancesForPool(poolID string) []params.Instance {
i.mux.Lock()
defer i.mux.Unlock()
var filteredInstances []params.Instance
for _, instance := range i.cache {
if instance.PoolID == poolID {
filteredInstances = append(filteredInstances, instance)
}
}
sortByCreationDate(filteredInstances)
return filteredInstances
}
func (i *InstanceCache) GetInstancesForScaleSet(scaleSetID uint) []params.Instance {
i.mux.Lock()
defer i.mux.Unlock()
var filteredInstances []params.Instance
for _, instance := range i.cache {
if instance.ScaleSetID == scaleSetID {
filteredInstances = append(filteredInstances, instance)
}
}
sortByCreationDate(filteredInstances)
return filteredInstances
}
func SetInstanceCache(instance params.Instance) {
instanceCache.SetInstance(instance)
}
func GetInstanceCache(name string) (params.Instance, bool) {
return instanceCache.GetInstance(name)
}
func DeleteInstanceCache(name string) {
instanceCache.DeleteInstance(name)
}
func GetAllInstancesCache() []params.Instance {
return instanceCache.GetAllInstances()
}
func GetInstancesForPool(poolID string) []params.Instance {
return instanceCache.GetInstancesForPool(poolID)
}
func GetInstancesForScaleSet(scaleSetID uint) []params.Instance {
return instanceCache.GetInstancesForScaleSet(scaleSetID)
}