statping/handlers/cache.go

114 lines
2.0 KiB
Go
Raw Normal View History

2018-10-21 19:36:11 +00:00
package handlers
import (
2020-03-09 18:17:55 +00:00
"github.com/statping/statping/utils"
2018-10-21 19:36:11 +00:00
"sync"
"time"
)
2018-11-05 22:04:06 +00:00
var CacheStorage Cacher
2018-10-21 19:36:11 +00:00
type Cacher interface {
Get(key string) []byte
2018-11-05 22:04:06 +00:00
Delete(key string)
2018-10-21 19:36:11 +00:00
Set(key string, content []byte, duration time.Duration)
List() map[string]Item
2020-02-04 06:37:32 +00:00
Lock()
Unlock()
2020-02-19 04:07:22 +00:00
StopRoutine()
2018-10-21 19:36:11 +00:00
}
// Item is a cached reference
type Item struct {
Content []byte
Expiration int64
}
2020-02-19 04:07:22 +00:00
// cleanRoutine is a go routine to automatically remove expired caches that haven't been hit recently
func cleanRoutine(s *Storage) {
duration := 5 * time.Second
CacheRoutine:
for {
select {
case <-s.running:
break CacheRoutine
case <-time.After(duration):
duration = 5 * time.Second
for k, v := range s.List() {
if v.Expired() {
s.Delete(k)
}
2020-02-04 06:37:32 +00:00
}
}
}
}
2018-10-21 19:36:11 +00:00
// Expired returns true if the item has expired.
func (item Item) Expired() bool {
if item.Expiration == 0 {
return false
}
return utils.Now().UnixNano() > item.Expiration
2018-10-21 19:36:11 +00:00
}
//Storage mecanism for caching strings in memory
type Storage struct {
2020-02-19 04:07:22 +00:00
items map[string]Item
mu *sync.RWMutex
running chan bool
2018-10-21 19:36:11 +00:00
}
2018-11-05 22:04:06 +00:00
//NewStorage creates a new in memory CacheStorage
2018-10-21 19:36:11 +00:00
func NewStorage() *Storage {
2020-02-19 04:07:22 +00:00
storage := &Storage{
items: make(map[string]Item),
mu: &sync.RWMutex{},
running: make(chan bool),
2018-10-21 19:36:11 +00:00
}
2020-02-19 04:07:22 +00:00
go cleanRoutine(storage)
return storage
}
func (s Storage) StopRoutine() {
close(s.running)
2018-10-21 19:36:11 +00:00
}
2020-02-04 06:37:32 +00:00
func (s Storage) Lock() {
s.mu.Lock()
}
func (s Storage) Unlock() {
s.mu.Unlock()
}
func (s Storage) List() map[string]Item {
return s.items
}
2018-10-21 19:36:11 +00:00
//Get a cached content by key
func (s Storage) Get(key string) []byte {
item := s.items[key]
if item.Expired() {
CacheStorage.Delete(key)
2018-10-21 19:36:11 +00:00
return nil
}
return item.Content
}
2018-11-05 22:04:06 +00:00
func (s Storage) Delete(key string) {
s.mu.Lock()
defer s.mu.Unlock()
2018-11-05 22:04:06 +00:00
delete(s.items, key)
}
2018-10-21 19:36:11 +00:00
//Set a cached content by key
func (s Storage) Set(key string, content []byte, duration time.Duration) {
s.mu.Lock()
defer s.mu.Unlock()
s.items[key] = Item{
Content: content,
Expiration: utils.Now().Add(duration).UnixNano(),
2018-10-21 19:36:11 +00:00
}
}