passed/storage/ram.go
2024-10-30 11:17:48 +01:00

92 lines
1.5 KiB
Go

package storage
import (
"sync"
"time"
)
func NewRamStore(clearInterval time.Duration) Store {
store := &ram{
clearInterval: clearInterval,
passwords: make(map[string]entry),
lock: sync.Mutex{},
close: make(chan bool),
}
go store.clearExpired()
return store
}
type ram struct {
clearInterval time.Duration
passwords map[string]entry
lock sync.Mutex
close chan bool
}
func (store *ram) Create(password []byte, expiresAt time.Time) (string, error) {
store.lock.Lock()
defer store.lock.Unlock()
for range 1000 {
id := generateId(24)
_, found := store.passwords[id]
if found {
continue
}
store.passwords[id] = entry{
Password: password,
ExpiresAt: expiresAt,
}
return id, nil
}
return "", ErrFull
}
func (store *ram) Get(id string) ([]byte, error) {
store.lock.Lock()
defer store.lock.Unlock()
password, found := store.passwords[id]
if !found {
return nil, ErrNotFound
}
return password.Password, nil
}
func (store *ram) Delete(id string) error {
delete(store.passwords, id)
return nil
}
func (store *ram) Close() error {
store.close <- true
return nil
}
func (store *ram) clearExpired() error {
ticker := time.NewTicker(store.clearInterval)
defer ticker.Stop()
for {
select {
case <-store.close:
return nil
case <-ticker.C:
store.lock.Lock()
time := time.Now()
for id, password := range store.passwords {
if time.After(password.ExpiresAt) {
store.Delete(id)
}
}
store.lock.Unlock()
}
}
}