89 lines
1.7 KiB
Go
89 lines
1.7 KiB
Go
package storage
|
|
|
|
import "errors"
|
|
import "io/ioutil"
|
|
import "os"
|
|
import "strings"
|
|
import "sync"
|
|
|
|
import "github.com/sneak/feta/toot"
|
|
|
|
type TootStorageBackend interface {
|
|
TootExists(t toot.Toot) bool
|
|
StoreToot(t toot.Toot) error
|
|
StoreToots(tc []*toot.Toot) error
|
|
}
|
|
|
|
type TootFSStorage struct {
|
|
root string
|
|
}
|
|
|
|
func NewTootFSStorage(root string) *TootFSStorage {
|
|
ts := new(TootFSStorage)
|
|
ts.root = root
|
|
return ts
|
|
}
|
|
|
|
func (ts *TootFSStorage) StoreToots(tc []*toot.Toot) error {
|
|
var returnErrors []string
|
|
for _, item := range tc {
|
|
err := ts.StoreToot(*item)
|
|
if err != nil {
|
|
returnErrors = append(returnErrors, err.Error())
|
|
continue
|
|
}
|
|
}
|
|
if len(returnErrors) == 0 {
|
|
return nil
|
|
}
|
|
return errors.New(strings.Join(returnErrors, "; "))
|
|
}
|
|
|
|
func (ts *TootFSStorage) TootExists(t toot.Toot) bool {
|
|
path := t.DiskStoragePath()
|
|
full := ts.root + "/" + path
|
|
_, err := os.Stat(full)
|
|
if os.IsNotExist(err) {
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (ts *TootFSStorage) StoreToot(t toot.Toot) error {
|
|
path := t.DiskStoragePath()
|
|
full := ts.root + "/" + path
|
|
return ioutil.WriteFile(full, t.Original, 0644)
|
|
}
|
|
|
|
type TootMemoryStorage struct {
|
|
sync.Mutex
|
|
toots map[toot.TootHash]toot.Toot
|
|
//maxSize uint // FIXME support eviction
|
|
}
|
|
|
|
func NewTootMemoryStorage() *TootMemoryStorage {
|
|
ts := new(TootMemoryStorage)
|
|
ts.toots = make(map[toot.TootHash]toot.Toot)
|
|
return ts
|
|
}
|
|
|
|
func (ts *TootMemoryStorage) StoreToot(t toot.Toot) {
|
|
th := t.Hash
|
|
if ts.TootExists(th) {
|
|
return
|
|
}
|
|
ts.Lock()
|
|
defer ts.Unlock()
|
|
ts.toots[th] = t
|
|
return
|
|
}
|
|
|
|
func (ts *TootMemoryStorage) TootExists(th toot.TootHash) bool {
|
|
ts.Lock()
|
|
defer ts.Unlock()
|
|
if _, ok := ts.toots[th]; ok { //this syntax is so gross
|
|
return true
|
|
}
|
|
return false
|
|
}
|