feat: use OS conform path for storing cached results

Instead of storing cached values in the config yaml, they are now stored
under these OS specific locations:
* Linux: `~/.cache/k8sgpt`
* MacOS: `~/Library/Caches`
* Windows: `%LocalAppData%\cache`

Additionally a `Cache` package and interface has been introduced.
Currently there are two implementations:
* Noop - Doesn't do anything
* FileBased - Stores data in files under the locations listed above

fixes #323

Signed-off-by: Patrick Pichler <git@patrickpichler.dev>
This commit is contained in:
Patrick Pichler
2023-04-24 18:41:54 +02:00
parent c3cc413e7f
commit 7eddb8f4a6
7 changed files with 133 additions and 35 deletions

View File

@@ -20,12 +20,12 @@ import (
"fmt"
"strings"
"github.com/k8sgpt-ai/k8sgpt/pkg/cache"
"github.com/k8sgpt-ai/k8sgpt/pkg/util"
"github.com/sashabaranov/go-openai"
"github.com/fatih/color"
"github.com/spf13/viper"
)
type OpenAIClient struct {
@@ -70,15 +70,20 @@ func (c *OpenAIClient) GetCompletion(ctx context.Context, prompt string) (string
return resp.Choices[0].Message.Content, nil
}
func (a *OpenAIClient) Parse(ctx context.Context, prompt []string, nocache bool) (string, error) {
func (a *OpenAIClient) Parse(ctx context.Context, prompt []string, cache cache.ICache) (string, error) {
inputKey := strings.Join(prompt, " ")
// Check for cached data
sEnc := base64.StdEncoding.EncodeToString([]byte(inputKey))
cacheKey := util.GetCacheKey(a.GetName(), a.language, sEnc)
// find in viper cache
if viper.IsSet(cacheKey) && !nocache {
if cache.Exists(cacheKey) {
// retrieve data from cache
response := viper.GetString(cacheKey)
response, err := cache.Load(cacheKey)
if err != nil {
return "", err
}
if response == "" {
color.Red("error retrieving cached data")
return "", nil
@@ -96,13 +101,13 @@ func (a *OpenAIClient) Parse(ctx context.Context, prompt []string, nocache bool)
return "", err
}
if !viper.IsSet(cacheKey) || nocache {
viper.Set(cacheKey, base64.StdEncoding.EncodeToString([]byte(response)))
if err := viper.WriteConfig(); err != nil {
color.Red("error writing config: %v", err)
return "", nil
}
err = cache.Store(cacheKey, base64.StdEncoding.EncodeToString([]byte(response)))
if err != nil {
color.Red("error storing value to cache: %v", err)
return "", nil
}
return response, nil
}