Nuestro burocrata preferido: Sam Lowry https://lowry.sindominio.net
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

105 lines
2.0 KiB

package db
import (
"encoding/json"
"log"
"time"
"go.etcd.io/bbolt"
)
// DB to store the status of lowry
type DB struct {
bolt *bbolt.DB
}
// Init database storing it in path
func Init(path string) (*DB, error) {
bolt, err := bbolt.Open(path, 0660, nil)
if err != nil {
return nil, err
}
err = bolt.Update(func(tx *bbolt.Tx) error {
for _, bucket := range [][]byte{inviteBucket, accountBucket} {
_, err := tx.CreateBucketIfNotExists(bucket)
if err != nil {
return err
}
}
return nil
})
if err != nil {
bolt.Close()
return nil, err
}
return &DB{bolt}, nil
}
// Close the database
func (db *DB) Close() {
db.bolt.Close()
}
func (db *DB) put(bucket []byte, key string, value interface{}) error {
encodedValue, err := json.Marshal(value)
if err != nil {
return err
}
return db.bolt.Update(func(tx *bbolt.Tx) error {
b := tx.Bucket(bucket)
return b.Put([]byte(key), encodedValue)
})
}
func (db *DB) get(bucket []byte, key string, value interface{}) error {
var encodedValue []byte
db.bolt.View(func(tx *bbolt.Tx) error {
b := tx.Bucket(bucket)
encodedValue = b.Get([]byte(key))
return nil
})
if encodedValue == nil {
return notFoundError{}
}
return json.Unmarshal(encodedValue, value)
}
func (db *DB) del(bucket []byte, key string) error {
return db.bolt.Update(func(tx *bbolt.Tx) error {
b := tx.Bucket(bucket)
return b.Delete([]byte(key))
})
}
func (db *DB) expire(bucket []byte, duration time.Duration) error {
var value struct {
CreationDate time.Time
}
return db.bolt.Update(func(tx *bbolt.Tx) error {
b := tx.Bucket(bucket)
return b.ForEach(func(k, v []byte) error {
err := json.Unmarshal(v, &value)
if err != nil {
log.Printf("Error unmarshalling %s: %v", string(k), err)
return nil
}
if value.CreationDate.Add(duration).Before(time.Now()) {
return b.Delete(k)
}
return nil
})
})
}
type notFoundError struct{}
func (e notFoundError) Error() string {
return "Not found"
}