11package store
22
33import (
4- "crypto/sha256"
54 "os"
65 "path/filepath"
76 "sync"
87 "time"
98
109 "github.com/ProtonMail/gluon/imap"
10+ "github.com/ProtonMail/gluon/internal/hash"
1111 "github.com/dgraph-io/badger/v3"
1212 "github.com/sirupsen/logrus"
1313)
1414
1515type BadgerStore struct {
16- db * badger.DB
17- gcExitCh chan struct {}
18- wg sync.WaitGroup
16+ db * badger.DB
17+ stopCh chan struct {}
18+ stopWG sync.WaitGroup
1919}
2020
2121type badgerTransaction struct {
2222 tx * badger.Txn
2323}
2424
25- func NewBadgerStore (path string , userID string , encryptionPassphrase []byte ) (* BadgerStore , error ) {
26- encryptionKey := sha256 .Sum256 (encryptionPassphrase )
27-
25+ func NewBadgerStore (path string , userID string , passphrase []byte ) (* BadgerStore , error ) {
2826 db , err := badger .Open (badger .DefaultOptions (filepath .Join (path , userID )).
2927 WithLogger (logrus .StandardLogger ()).
3028 WithLoggingLevel (badger .ERROR ).
31- WithEncryptionKey (encryptionKey [:] ).
29+ WithEncryptionKey (hash . SHA256 ( passphrase ) ).
3230 WithIndexCacheSize (128 * 1024 * 1024 ),
3331 )
3432 if err != nil {
3533 return nil , err
3634 }
3735
38- store := & BadgerStore {db : db , gcExitCh : make (chan struct {})}
36+ store := & BadgerStore {
37+ db : db ,
38+ stopCh : make (chan struct {}),
39+ }
3940
4041 store .startGCCollector ()
4142
@@ -45,24 +46,27 @@ func NewBadgerStore(path string, userID string, encryptionPassphrase []byte) (*B
4546func (b * BadgerStore ) startGCCollector () {
4647 // Garbage collection needs to be run manually by us at some point.
4748 // See https://dgraph.io/docs/badger/get-started/#garbage-collection for more details.
48- b .wg .Add (1 )
49+ b .stopWG .Add (1 )
4950
5051 go func () {
51- defer b .wg .Done ()
52-
53- gcRun := time .After (5 * time .Minute )
54-
55- select {
56- case <- gcRun :
57- {
58- again:
59- err := b .db .RunValueLogGC (0.7 )
60- if err == nil {
61- goto again
52+ defer b .stopWG .Done ()
53+
54+ ticker := time .NewTicker (5 * time .Minute )
55+ defer ticker .Stop ()
56+
57+ for {
58+ select {
59+ case <- ticker .C :
60+ {
61+ again:
62+ if err := b .db .RunValueLogGC (0.5 ); err == nil {
63+ goto again
64+ }
6265 }
66+
67+ case <- b .stopCh :
68+ return
6369 }
64- case <- b .gcExitCh :
65- return
6670 }
6771 }()
6872}
@@ -118,8 +122,9 @@ func (b *badgerTransaction) Rollback() error {
118122}
119123
120124func (b * BadgerStore ) Close () error {
121- close (b .gcExitCh )
122- b .wg .Wait ()
125+ close (b .stopCh )
126+
127+ b .stopWG .Wait ()
123128
124129 return b .db .Close ()
125130}
0 commit comments