snow/person/cache.go

95 lines
1.5 KiB
Go
Raw Normal View History

package person
2023-10-31 22:40:14 +00:00
import (
"fmt"
2023-10-31 22:40:14 +00:00
"sync"
"time"
)
var (
cache *PersonsCache
)
2023-10-31 22:40:14 +00:00
type CacheEntry struct {
Entry *Person
2023-10-31 22:40:14 +00:00
LastAccessed time.Time
}
type PersonsCache struct {
sync.Map
}
func NewPersonsCacheMutex() *PersonsCache {
return &PersonsCache{}
}
func (m *PersonsCache) CacheKiller() {
for {
if m.Count() == 0 {
2023-10-31 22:40:14 +00:00
continue
}
m.Range(func(key, value interface{}) bool {
2023-10-31 22:40:14 +00:00
cacheEntry := value.(*CacheEntry)
2023-11-02 17:50:52 +00:00
if time.Since(cacheEntry.LastAccessed) >= 30 * time.Minute {
m.Delete(key)
2023-10-31 22:40:14 +00:00
}
return true
})
2023-11-02 17:50:52 +00:00
time.Sleep(5000 * time.Minute)
2023-10-31 22:40:14 +00:00
}
}
func (m *PersonsCache) GetPerson(id string) *Person {
2023-10-31 22:40:14 +00:00
if p, ok := m.Load(id); ok {
fmt.Println("Cache hit", id)
2023-10-31 22:40:14 +00:00
cacheEntry := p.(*CacheEntry)
return cacheEntry.Entry
2023-10-31 22:40:14 +00:00
}
return nil
}
func (m *PersonsCache) GetPersonByDisplay(displayName string) *Person {
var person *Person
m.RangeEntry(func(key string, value *CacheEntry) bool {
if value.Entry.DisplayName == displayName {
person = value.Entry
return false
}
return true
})
return person
}
func (m *PersonsCache) SavePerson(p *Person) {
2023-10-31 22:40:14 +00:00
m.Store(p.ID, &CacheEntry{
Entry: p,
LastAccessed: time.Now(),
})
}
func (m *PersonsCache) DeletePerson(id string) {
m.Delete(id)
}
func (m *PersonsCache) RangeEntry(f func(key string, value *CacheEntry) bool) {
2023-10-31 22:40:14 +00:00
m.Range(func(key, value interface{}) bool {
return f(key.(string), value.(*CacheEntry))
2023-10-31 22:40:14 +00:00
})
}
func (m *PersonsCache) Count() int {
count := 0
m.Range(func(key, value interface{}) bool {
count++
return true
})
return count
}