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.
lowry/db/community.go

73 lines
1.7 KiB

package db
import (
"encoding/json"
"errors"
"log"
"time"
"go.etcd.io/bbolt"
)
var (
communityBucket = []byte("community")
)
type community struct {
Name string
CreationDate time.Time
}
// AddCommunity stores in the db the community that was created by host
func (db *DB) AddCommunity(name string, host string) error {
var communities []community
err := db.get(communityBucket, host, &communities)
if err != nil && !errors.Is(err, notFoundError{}) {
return err
}
communities = append(communities, community{name, time.Now()})
return db.put(communityBucket, host, communities)
}
// CountCommunities returns the nubmer of communities created by host
func (db *DB) CountCommunities(host string) (int, error) {
var communities []community
err := db.get(communityBucket, host, &communities)
if errors.Is(err, notFoundError{}) {
return 0, nil
}
return len(communities), err
}
// ExpireCommunities older than duration
func (db *DB) ExpireCommunities(duration time.Duration) error {
return db.bolt.Update(func(tx *bbolt.Tx) error {
b := tx.Bucket(communityBucket)
return b.ForEach(func(k, v []byte) error {
var communities []community
err := json.Unmarshal(v, &communities)
if err != nil {
log.Printf("Error unmarshalling %s: %v", string(k), err)
return nil
}
newCommunities := []community{}
for _, c := range communities {
if c.CreationDate.Add(duration).After(time.Now()) {
newCommunities = append(newCommunities, c)
}
}
if len(newCommunities) == len(communities) {
return nil
}
encodedValue, err := json.Marshal(newCommunities)
if err != nil {
return err
}
return b.Put(k, encodedValue)
})
})
}