summaryrefslogtreecommitdiff
path: root/middleware/session/bbolt.go
blob: 1068ed87c3af6cc27e0358674e9fac8e2dc45d20 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package session

import (
	"bytes"
	"context"
	"encoding/gob"
	"log/slog"

	"go.etcd.io/bbolt"
)

func New(db *bbolt.DB, bucketName []byte) Store {
	return &BoltStore{
		db:         db,
		bucketName: bucketName,
	}
}

type BoltStore struct {
	db         *bbolt.DB
	bucketName []byte
}

func (s *BoltStore) Load(ctx context.Context, sessionID string) Value {
	v := Value{}
	err := s.db.View(func(tx *bbolt.Tx) error {
		bucket := tx.Bucket(s.bucketName)
		if bucket == nil {
			// no bucket -- normal situation
			return nil
		}
		vb := bucket.Get([]byte(sessionID))
		if vb == nil {
			// no session -- no error
			return nil
		}
		rdr := bytes.NewBuffer(vb)

		return gob.NewDecoder(rdr).Decode(&v)
	})
	if err != nil {
		slog.WarnContext(ctx, "failed load session", slog.Any("error", err))
	}
	return v
}

func (s *BoltStore) Save(ctx context.Context, sessionID string, value Value) error {
	return s.db.Update(func(tx *bbolt.Tx) error {
		bucket, err := tx.CreateBucketIfNotExists(s.bucketName)
		if err != nil {
			return err
		}
		wrt := bytes.NewBuffer([]byte{})
		if err := gob.NewEncoder(wrt).Encode(value); err != nil {
			return err
		}

		return bucket.Put([]byte(sessionID), wrt.Bytes())
	})
}

func (s *BoltStore) Remove(ctx context.Context, sessionID string) error {
	return s.db.Update(func(tx *bbolt.Tx) error {
		bucket, err := tx.CreateBucketIfNotExists(s.bucketName)
		if err != nil {
			return err
		}

		return bucket.Delete([]byte(sessionID))
	})
}