2021-07-24 17:46:22 +02:00
|
|
|
// ___ ____ ___ ___
|
|
|
|
// \ \ / / | _ | __| \ \ / / || | __ || || _ |
|
|
|
|
// \ \/ / |___ | |__ \ \/ / || |___ || ||___|
|
|
|
|
// \ / | _ | _ | \ / || __ | || ||\\
|
|
|
|
// \/ |___ |___ | \/ || ____| || || \\
|
|
|
|
//
|
|
|
|
// Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License
|
|
|
|
// Repo: https://git.pbiernat.dev/golang/vegvisir
|
|
|
|
|
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2021-07-25 01:44:50 +02:00
|
|
|
"time"
|
2021-07-24 17:46:22 +02:00
|
|
|
)
|
|
|
|
|
2021-08-03 00:13:14 +02:00
|
|
|
// TTLItem struct
|
|
|
|
type TTLItem struct {
|
2021-07-25 01:44:50 +02:00
|
|
|
ts int // timestamp
|
2021-07-25 20:13:03 +02:00
|
|
|
ttl int // ttl in seconds
|
2021-07-25 01:44:50 +02:00
|
|
|
}
|
|
|
|
|
2021-08-03 00:13:14 +02:00
|
|
|
// NewMemoryDatastore function
|
2021-07-24 17:46:22 +02:00
|
|
|
func NewMemoryDatastore() *MemoryDatastore {
|
|
|
|
return &MemoryDatastore{
|
|
|
|
cache: make(map[string]interface{}),
|
2021-08-03 00:13:14 +02:00
|
|
|
ts: make(map[string]TTLItem),
|
2021-07-24 17:46:22 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-03 00:13:14 +02:00
|
|
|
// MemoryDatastore struct
|
2021-07-24 17:46:22 +02:00
|
|
|
type MemoryDatastore struct {
|
|
|
|
cache map[string]interface{}
|
2021-08-03 00:13:14 +02:00
|
|
|
ts map[string]TTLItem
|
2021-07-24 17:46:22 +02:00
|
|
|
}
|
|
|
|
|
2021-08-03 00:13:14 +02:00
|
|
|
// SetKey function
|
2021-07-24 17:46:22 +02:00
|
|
|
func (ds *MemoryDatastore) SetKey(key string, data interface{}, ttl int) error {
|
|
|
|
ds.cache[key] = data
|
2021-08-03 00:13:14 +02:00
|
|
|
ds.ts[key] = TTLItem{
|
2021-07-25 01:44:50 +02:00
|
|
|
ts: time.Now().Second(),
|
|
|
|
ttl: ttl,
|
|
|
|
}
|
2021-07-24 17:46:22 +02:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-08-03 00:13:14 +02:00
|
|
|
// GetKey function
|
2021-07-24 17:46:22 +02:00
|
|
|
func (ds *MemoryDatastore) GetKey(key string) (interface{}, error) {
|
2021-07-25 01:44:50 +02:00
|
|
|
ds.gc(key) // remove key is time of creation is outdated
|
|
|
|
|
2021-07-24 17:46:22 +02:00
|
|
|
if data, ok := ds.cache[key]; ok {
|
|
|
|
return data, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, errors.New("Key not found" + key)
|
|
|
|
}
|
|
|
|
|
2021-08-03 00:13:14 +02:00
|
|
|
// IsConnected function
|
2021-07-24 17:46:22 +02:00
|
|
|
func (ds *MemoryDatastore) IsConnected() bool {
|
|
|
|
return true
|
|
|
|
}
|
2021-07-25 01:44:50 +02:00
|
|
|
|
|
|
|
func (ds *MemoryDatastore) gc(key string) {
|
|
|
|
if item, ok := ds.ts[key]; ok && item.ts < time.Now().Second()-item.ttl {
|
|
|
|
delete(ds.cache, key)
|
|
|
|
}
|
|
|
|
}
|