Skip to content

Commit

Permalink
Add prototype of API Response Caching
Browse files Browse the repository at this point in the history
  • Loading branch information
seokho-son committed Sep 5, 2023
1 parent 1c19880 commit 49c3bcb
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 11 deletions.
71 changes: 65 additions & 6 deletions src/core/common/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,31 +16,74 @@ package common

import (
"fmt"
"sync"
"time"

"github.com/go-resty/resty/v2"
)

func ExecuteHttpRequest(
// CacheItem is a struct to store cached item
type CacheItem[T any] struct {
Response T
ExpiresAt time.Time
}

var clientCache = sync.Map{}

const (
// ShortDuration is a duration for short-term cache
ShortDuration = 2 * time.Second
// MediumDuration is a duration for medium-term cache
MediumDuration = 5 * time.Second
// LongDuration is a duration for long-term cache
LongDuration = 10 * time.Second
)

// ExecuteHttpRequest performs the HTTP request and fills the result
func ExecuteHttpRequest[T any](
client *resty.Client,
method string,
url string,
headers map[string]string,
body interface{},
result interface{}) error {
result *T, // Generic type
cacheDuration time.Duration,
) error {

req := client.R().SetResult(result)
// Generate cache key for GET method only
cacheKey := ""
if method == "GET" {
cacheKey = fmt.Sprintf("%s_%s", method, url)
if item, found := clientCache.Load(cacheKey); found {
cachedItem := item.(CacheItem[T]) // Generic type
if time.Now().Before(cachedItem.ExpiresAt) {
fmt.Println("Cache hit! Expires: ", time.Now().Sub(cachedItem.ExpiresAt))
*result = cachedItem.Response
//val := reflect.ValueOf(result).Elem()
//cachedVal := reflect.ValueOf(cachedItem.Response)
//val.Set(cachedVal)

return nil
} else {
fmt.Println("Cache item expired!")
clientCache.Delete(cacheKey)
}
}
}

// Perform the HTTP request using Resty
req := client.R().SetResult(result)
if headers != nil {
req = req.SetHeaders(headers)
}

if body != nil {
req = req.SetBody(body)
}

var resp *resty.Response
var err error

// Execute HTTP method based on the given type
switch method {
case "GET":
resp, err = req.Get(url)
Expand All @@ -55,10 +98,26 @@ func ExecuteHttpRequest(
}

if err != nil {
return err
return fmt.Errorf("[Error from: %s] Message: %s", url, err.Error())
}

if resp.IsError() {
return fmt.Errorf("API error: %s", resp.Status())
return fmt.Errorf("[Error from: %s] Status code: %s", url, resp.Status())
}

// Update the cache for GET method only
if method == "GET" {

//val := reflect.ValueOf(result).Elem()
//newCacheItem := val.Interface()

// Check if result is nil
if result == nil {
fmt.Println("Warning: result is nil, not caching.")
} else {
clientCache.Store(cacheKey, CacheItem[T]{Response: *result, ExpiresAt: time.Now().Add(cacheDuration)})
fmt.Println("Cached successfully!")
}
}

return nil
Expand Down
11 changes: 6 additions & 5 deletions src/core/common/utility.go
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ func GetCloudLocation(cloudType string, nativeRegion string) GeoLocation {

key := "/cloudtype/" + cloudType + "/region/" + nativeRegion

fmt.Printf("[GetCloudLocation] KEY: %+v\n", key)
//fmt.Printf("[GetCloudLocation] KEY: %+v\n", key)

keyValue, err := CBStore.Get(key)

Expand Down Expand Up @@ -468,12 +468,13 @@ func GetConnConfigList() (ConnConfigList, error) {
url,
nil,
nil,
&callResult)
&callResult,
MediumDuration,
)

if err != nil {
CBLog.Error(err)
content := ConnConfigList{}
err := fmt.Errorf("Error from CB-Spider: " + err.Error())
return content, err
}

Expand Down Expand Up @@ -560,14 +561,14 @@ func GetNativeRegion(connectionName string) (string, error) {
if connectionName != row[1] {
continue
}
fmt.Println("Found a line for the connectionName from file: " + row[1])
//fmt.Println("Found a line for the connectionName from file: " + row[1])
}

if connectionName != "" {
// After finish handling line for the connectionName, break
if connectionName == row[1] {
nativeRegionName = row[3]
fmt.Println("Handled for the connectionName from file: " + row[1])
//fmt.Println("Handled for the connectionName from file: " + row[1])
break
}
}
Expand Down

0 comments on commit 49c3bcb

Please sign in to comment.