Skip to content

Commit

Permalink
chore: add cache for connection objects
Browse files Browse the repository at this point in the history
  • Loading branch information
yashmehrotra authored and moshloop committed Feb 5, 2024
1 parent 8cb000a commit 5441dc5
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion context/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,15 @@ import (
"fmt"
"net/url"
"strings"
"time"

"github.com/eko/gocache/lib/v4/cache"
"github.com/eko/gocache/lib/v4/store"
gocache_store "github.com/eko/gocache/store/go_cache/v4"
"github.com/flanksource/duty/models"
"github.com/flanksource/gomplate/v3"
"github.com/google/uuid"
gocache "github.com/patrickmn/go-cache"
"gorm.io/gorm"
)

Expand Down Expand Up @@ -46,6 +51,12 @@ func extractConnectionNameType(connectionString string) (name, namespace, connec
return
}

var connectionCache = cache.New[*models.Connection](gocache_store.NewGoCache(gocache.New(30*time.Minute, 30*time.Minute)))

func getConnectionCacheKey(connString, ctxNamespace string) string {
return connString + ctxNamespace
}

// HydrateConnectionByURL retrieves a connection from the given connection string.
// The connection string is expected to be in one of the following forms:
// - connection://<type>/<name> or connection://<type>/<namespace>/<name>
Expand All @@ -55,6 +66,11 @@ func HydrateConnectionByURL(ctx Context, connectionString string) (*models.Conne
return nil, nil
}

cacheKey := getConnectionCacheKey(connectionString, ctx.GetNamespace())
if cacheVal, err := connectionCache.Get(ctx, cacheKey); err == nil {
return cacheVal, nil
}

// Must be in one of the correct forms.
if _, err := uuid.Parse(connectionString); err != nil && !strings.HasPrefix(connectionString, "connection://") {
if _url, err := url.Parse(connectionString); err == nil {
Expand All @@ -70,10 +86,16 @@ func HydrateConnectionByURL(ctx Context, connectionString string) (*models.Conne
}

if connection == nil {
// Setting a smaller cache for connection not found
_ = connectionCache.Set(ctx, cacheKey, connection, store.WithExpiration(5*time.Minute))
return nil, nil
}

return HydrateConnection(ctx, connection)
hydratedConnection, err := HydrateConnection(ctx, connection)
if err == nil {
_ = connectionCache.Set(ctx, cacheKey, hydratedConnection)
}
return hydratedConnection, err
}

func IsValidConnectionURL(connectionString string) bool {
Expand Down

0 comments on commit 5441dc5

Please sign in to comment.