Add insert link to cache

Add DisableLinkCaching config
This commit is contained in:
Chun-Hung Tseng
2023-07-12 22:50:39 +02:00
parent e330ee8276
commit d293198b51
3 changed files with 64 additions and 0 deletions

View File

@@ -2,15 +2,72 @@ package proton_api_bridge
import (
"context"
"sync"
"github.com/henrybear327/go-proton-api"
)
type cacheEntry struct {
link *proton.Link
}
type cache struct {
data map[string]*cacheEntry
disableCaching bool
sync.RWMutex
}
func newCache(disableCaching bool) *cache {
return &cache{
data: make(map[string]*cacheEntry),
disableCaching: disableCaching,
}
}
func (linkCache *cache) _getLink(linkID string) *proton.Link {
if linkCache.disableCaching {
return nil
}
linkCache.RLock()
defer linkCache.RUnlock()
if data, ok := linkCache.data[linkID]; ok && data.link != nil {
return data.link
}
return nil
}
func (linkCache *cache) _insertLink(linkID string, link *proton.Link) {
if linkCache.disableCaching {
return
}
linkCache.Lock()
defer linkCache.Unlock()
linkCache.data[linkID] = &cacheEntry{
link: link,
}
}
func (protonDrive *ProtonDrive) getLink(ctx context.Context, linkID string) (*proton.Link, error) {
// attempt to get from cache first
if link := protonDrive.cache._getLink(linkID); link != nil {
// log.Println("From cache")
return link, nil
}
// log.Println("Not from cache")
// no cached data, fetch
link, err := protonDrive.c.GetLink(ctx, protonDrive.MainShare.ShareID, linkID)
if err != nil {
return nil, err
}
// populate cache
protonDrive.cache._insertLink(linkID, &link)
return &link, nil
}

View File

@@ -17,6 +17,7 @@ type Config struct {
DestructiveIntegrationTest bool // CAUTION: the integration test requires a clean proton drive
EmptyTrashAfterIntegrationTest bool // CAUTION: the integration test will clean up all the data in the trash
ReplaceExistingDraft bool // for the file upload replace or keep it as-is option
DisableCaching bool // link node caching
/* Drive */
DataFolderName string
@@ -57,6 +58,7 @@ func NewConfigWithDefaultValues() *Config {
DestructiveIntegrationTest: false,
EmptyTrashAfterIntegrationTest: false,
ReplaceExistingDraft: false,
DisableCaching: true,
DataFolderName: "data",
}
@@ -102,6 +104,7 @@ func NewConfigForIntegrationTests() *Config {
DestructiveIntegrationTest: true,
EmptyTrashAfterIntegrationTest: true,
ReplaceExistingDraft: false,
DisableCaching: false,
DataFolderName: "data",
}

View File

@@ -25,6 +25,8 @@ type ProtonDrive struct {
addrKRs map[string]*crypto.KeyRing
addrData []proton.Address
signatureAddress string
cache *cache
}
func NewDefaultConfig() *common.Config {
@@ -140,6 +142,8 @@ func NewProtonDrive(ctx context.Context, config *common.Config, authHandler prot
addrKRs: addrKRs,
addrData: addrData,
signatureAddress: mainShare.Creator,
cache: newCache(config.DisableCaching),
}, credentials, nil
}