2024-10-29 23:08:11 +00:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2024-10-29 23:25:53 +00:00
|
|
|
func NewRamStore(clearInterval time.Duration) Store {
|
2024-10-29 23:08:11 +00:00
|
|
|
store := &ram{
|
2024-10-29 23:25:53 +00:00
|
|
|
clearInterval: clearInterval,
|
|
|
|
passwords: make(map[string]entry),
|
|
|
|
lock: sync.Mutex{},
|
|
|
|
close: make(chan bool),
|
2024-10-29 23:08:11 +00:00
|
|
|
}
|
|
|
|
|
2024-10-29 23:21:25 +00:00
|
|
|
go store.clearExpired()
|
2024-10-29 23:08:11 +00:00
|
|
|
return store
|
|
|
|
}
|
|
|
|
|
|
|
|
type ram struct {
|
2024-10-29 23:25:53 +00:00
|
|
|
clearInterval time.Duration
|
|
|
|
passwords map[string]entry
|
|
|
|
lock sync.Mutex
|
|
|
|
close chan bool
|
2024-10-29 23:08:11 +00:00
|
|
|
}
|
|
|
|
|
2024-10-30 10:17:48 +00:00
|
|
|
func (store *ram) Create(password []byte, expiresAt time.Time) (string, error) {
|
2024-10-29 23:08:11 +00:00
|
|
|
store.lock.Lock()
|
|
|
|
defer store.lock.Unlock()
|
|
|
|
|
|
|
|
for range 1000 {
|
2024-10-30 09:09:18 +00:00
|
|
|
id := generateId(24)
|
2024-10-29 23:08:11 +00:00
|
|
|
_, found := store.passwords[id]
|
|
|
|
if found {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
store.passwords[id] = entry{
|
2024-10-30 09:09:18 +00:00
|
|
|
Password: password,
|
|
|
|
ExpiresAt: expiresAt,
|
2024-10-29 23:08:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return id, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return "", ErrFull
|
|
|
|
}
|
|
|
|
|
2024-10-30 10:17:48 +00:00
|
|
|
func (store *ram) Get(id string) ([]byte, error) {
|
2024-10-29 23:08:11 +00:00
|
|
|
store.lock.Lock()
|
|
|
|
defer store.lock.Unlock()
|
|
|
|
|
|
|
|
password, found := store.passwords[id]
|
|
|
|
if !found {
|
|
|
|
return nil, ErrNotFound
|
|
|
|
}
|
|
|
|
|
2024-10-30 09:09:18 +00:00
|
|
|
return password.Password, nil
|
2024-10-29 23:08:11 +00:00
|
|
|
}
|
|
|
|
|
2024-10-30 10:17:48 +00:00
|
|
|
func (store *ram) Delete(id string) error {
|
|
|
|
delete(store.passwords, id)
|
|
|
|
return nil
|
2024-10-29 23:36:53 +00:00
|
|
|
}
|
|
|
|
|
2024-10-29 23:21:25 +00:00
|
|
|
func (store *ram) Close() error {
|
|
|
|
store.close <- true
|
|
|
|
return nil
|
|
|
|
}
|
2024-10-29 23:08:11 +00:00
|
|
|
|
2024-10-29 23:21:25 +00:00
|
|
|
func (store *ram) clearExpired() error {
|
2024-10-29 23:25:53 +00:00
|
|
|
ticker := time.NewTicker(store.clearInterval)
|
2024-10-29 23:21:25 +00:00
|
|
|
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 {
|
2024-10-30 09:09:18 +00:00
|
|
|
if time.After(password.ExpiresAt) {
|
2024-10-30 10:17:48 +00:00
|
|
|
store.Delete(id)
|
2024-10-29 23:21:25 +00:00
|
|
|
}
|
|
|
|
}
|
2024-10-29 23:36:53 +00:00
|
|
|
|
|
|
|
store.lock.Unlock()
|
2024-10-29 23:08:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|