2024-10-29 23:08:11 +00:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2024-10-30 10:47:17 +00:00
|
|
|
func NewRamStore() Store {
|
2024-10-29 23:08:11 +00:00
|
|
|
store := &ram{
|
2024-10-30 10:51:20 +00:00
|
|
|
passwords: make(map[string]ramEntry),
|
2024-10-30 10:47:17 +00:00
|
|
|
lock: sync.Mutex{},
|
2024-10-29 23:08:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return store
|
|
|
|
}
|
|
|
|
|
|
|
|
type ram struct {
|
2024-10-30 10:51:20 +00:00
|
|
|
passwords map[string]ramEntry
|
2024-10-30 10:47:17 +00:00
|
|
|
lock sync.Mutex
|
2024-10-29 23:08:11 +00:00
|
|
|
}
|
|
|
|
|
2024-10-30 10:51:20 +00:00
|
|
|
type ramEntry struct {
|
|
|
|
Password []byte
|
|
|
|
ExpiresAt time.Time
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2024-10-30 10:51:20 +00:00
|
|
|
store.passwords[id] = ramEntry{
|
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-30 10:47:17 +00:00
|
|
|
func (store *ram) ClearExpired() error {
|
|
|
|
store.lock.Lock()
|
|
|
|
defer store.lock.Unlock()
|
|
|
|
time := time.Now()
|
2024-10-29 23:08:11 +00:00
|
|
|
|
2024-10-30 10:47:17 +00:00
|
|
|
for id, password := range store.passwords {
|
|
|
|
if time.After(password.ExpiresAt) {
|
|
|
|
err := store.Delete(id)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
2024-10-29 23:21:25 +00:00
|
|
|
}
|
2024-10-29 23:08:11 +00:00
|
|
|
}
|
|
|
|
}
|
2024-10-30 10:47:17 +00:00
|
|
|
|
|
|
|
return nil
|
2024-10-29 23:08:11 +00:00
|
|
|
}
|