Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new setting cacheDir #84

Merged
merged 4 commits into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,10 @@ The configuration object is a JSON document with the following structure:
"rpcUrl": "http://localhost:8545",
"stateContractAddr": "0xEA9aF2088B4a9770fC32A12fD42E61BDD317E655"
}
}
},
// Directory to cache time-consuming operations.
// If empty, use the default one in user's HOME directory.
"cacheDir": "/tmp/polygonid"
}
```

Expand Down
12 changes: 10 additions & 2 deletions badger_cache_engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ type cachedRemoteDocument struct {

type badgerCacheEngine struct {
embedDocs map[string]*ld.RemoteDocument
cacheDir string
}

func (m *badgerCacheEngine) Get(
Expand All @@ -30,7 +31,7 @@ func (m *badgerCacheEngine) Get(
}
}

db, cleanup, err := getCacheDB()
db, cleanup, err := getCacheDB(m.cacheDir)
if err != nil {
slog.Error("can't get cache database", "err", err)
return nil, time.Time{}, loaders.ErrCacheMiss
Expand Down Expand Up @@ -78,7 +79,7 @@ func (m *badgerCacheEngine) Set(key string, doc *ld.RemoteDocument,
}
}

db, cleanup, err := getCacheDB()
db, cleanup, err := getCacheDB(m.cacheDir)
if err != nil {
slog.Error("can't get cache database", "err", err)
return nil
Expand Down Expand Up @@ -122,6 +123,13 @@ func withEmbeddedDocumentBytes(u string, doc []byte) badgerCacheEngineOption {
}
}

func withCacheDir(cacheDir string) badgerCacheEngineOption {
return func(engine *badgerCacheEngine) error {
engine.cacheDir = cacheDir
return nil
}
}

func newBadgerCacheEngine(
opts ...badgerCacheEngineOption) (loaders.CacheEngine, error) {

Expand Down
95 changes: 61 additions & 34 deletions cache.go
Original file line number Diff line number Diff line change
@@ -1,28 +1,35 @@
package c_polygonid

import (
"errors"
"log/slog"
"os"
"path"
"path/filepath"
"sync"

"github.com/dgraph-io/badger/v4"
)

var badgerLogger badger.Logger = nil

var globalDB *badger.DB
var dbCnt int
var openedDBs = make(map[string]*badger.DB)
var openedDBsCnts = make(map[string]int)
var dbCond = sync.NewCond(&sync.Mutex{})

func CleanCache() (err error) {
func CleanCache(cacheDir string) (err error) {
cacheDir, err = createNormalizedCacheDir(cacheDir)
if err != nil {
return err
}

dbCond.L.Lock()
for dbCnt != 0 {
for openedDBsCnts[cacheDir] != 0 {
dbCond.Wait()
}
defer dbCond.L.Unlock()

db, err := openDB()
db, err := openDB(cacheDir)
if err != nil {
return err
}
Expand All @@ -40,11 +47,39 @@ func CleanCache() (err error) {
return db.DropAll()
}

func getCacheDB() (*badger.DB, func(), error) {
// Normalize the directory path and create it if it doesn't exist.
func createNormalizedCacheDir(d string) (string, error) {
if d == "" {
var err error
d, err = os.UserCacheDir()
if err != nil {
return "", err
}
}

normDir, err := filepath.EvalSymlinks(d)
if errors.Is(err, os.ErrNotExist) {
err = os.MkdirAll(d, 0700)
if err != nil {
return "", err
}
normDir, err = filepath.EvalSymlinks(d)
}

return normDir, err
}

func getCacheDB(cacheDir string) (*badger.DB, func(), error) {
var err error
cacheDir, err = createNormalizedCacheDir(cacheDir)
if err != nil {
return nil, nil, err
}

dbCond.L.Lock()
defer dbCond.L.Unlock()

err := maybeOpenDB()
err = maybeOpenDB(cacheDir)
if err != nil {
return nil, nil, err
}
Expand All @@ -57,48 +92,49 @@ func getCacheDB() (*badger.DB, func(), error) {
dbCond.L.Lock()
defer dbCond.L.Unlock()

dbCnt--
if dbCnt == 0 {
err2 := globalDB.Close()
cnt := openedDBsCnts[cacheDir]
cnt--
if cnt == 0 {
err2 := openedDBs[cacheDir].Close()
if err2 != nil {
slog.Error("failed to close db", "err", err2)
}
globalDB = nil
delete(openedDBs, cacheDir)
delete(openedDBsCnts, cacheDir)
} else {
openedDBsCnts[cacheDir] = cnt
}

dbCond.Broadcast()
})
}

return globalDB, releaseDB, nil
return openedDBs[cacheDir], releaseDB, nil
}

// If globalDB is nil, open a new DB, assign it to globalDB.
// Also increment dbCnt.
// If openedDBs[cacheDir] is nil, open a new DB and increment
// openedDBsCnts[cacheDir].
// DANGER: This function is not thread-safe and should be called only when
// dbCond.L is locked. Use getCacheDB() instead.
func maybeOpenDB() error {
if globalDB != nil {
dbCnt++
func maybeOpenDB(cacheDir string) error {
if openedDBs[cacheDir] != nil {
openedDBsCnts[cacheDir]++
return nil
}

db, err := openDB()
db, err := openDB(cacheDir)
if err != nil {
return err
}

globalDB = db
dbCnt = 1
openedDBs[cacheDir] = db
openedDBsCnts[cacheDir]++

return nil
}

func openDB() (*badger.DB, error) {
badgerPath, err := getBadgerPath()
if err != nil {
return nil, err
}
func openDB(cacheDir string) (*badger.DB, error) {
badgerPath := path.Join(cacheDir, "c-polygonid-cache")

opts := badger.DefaultOptions(badgerPath)
if badgerLogger != nil {
Expand All @@ -107,12 +143,3 @@ func openDB() (*badger.DB, error) {

return badger.Open(opts)
}

func getBadgerPath() (string, error) {
cachePath, err := os.UserCacheDir()
if err != nil {
return "", err
}
cachePath = path.Join(cachePath, "c-polygonid-cache")
return cachePath, nil
}
Loading