boltdb support.

This commit is contained in:
fiatjaf
2024-02-08 12:36:34 -03:00
parent 830d51e96d
commit 9d87d1fd8a
9 changed files with 647 additions and 0 deletions

54
bolt/save.go Normal file
View File

@@ -0,0 +1,54 @@
package bolt
import (
"context"
"encoding/binary"
"encoding/hex"
"fmt"
"github.com/boltdb/bolt"
"github.com/fiatjaf/eventstore"
"github.com/nbd-wtf/go-nostr"
nostr_binary "github.com/nbd-wtf/go-nostr/binary"
)
func (b *BoltBackend) SaveEvent(ctx context.Context, evt *nostr.Event) error {
// sanity checking
if evt.CreatedAt > maxuint32 || evt.Kind > maxuint16 {
return fmt.Errorf("event with values out of expected boundaries")
}
return b.db.Update(func(txn *bolt.Tx) error {
id, _ := hex.DecodeString(evt.ID)
// check if we already have this id
bucket := txn.Bucket(bucketId)
res := bucket.Get(id)
if res != nil {
return eventstore.ErrDupEvent
}
// encode to binary form so we'll save it
bin, err := nostr_binary.Marshal(evt)
if err != nil {
return err
}
// raw event store
raw := txn.Bucket(bucketRaw)
seq, _ := raw.NextSequence()
seqb := binary.BigEndian.AppendUint64(nil, seq)
if err := raw.Put(seqb, bin); err != nil {
return err
}
for _, km := range getIndexKeysForEvent(evt) {
bucket := txn.Bucket(km.bucket)
if err := bucket.Put(km.key, seqb); err != nil {
return err
}
}
return nil
})
}