-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Basic implementation of Caching Middleware
- Loading branch information
1 parent
69b86f0
commit 484f69e
Showing
23 changed files
with
1,493 additions
and
31 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
package cache | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"time" | ||
) | ||
|
||
var ErrNotFound = errors.New("value not found in the cache") | ||
|
||
type Cache interface { | ||
Set(ctx context.Context, key string, data []byte, expiration time.Duration) error | ||
Get(ctx context.Context, key string) ([]byte, error) | ||
Delete(ctx context.Context, key string) error | ||
Healthcheck(ctx context.Context) error | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
package cache | ||
|
||
import ( | ||
"context" | ||
"sync" | ||
"time" | ||
) | ||
|
||
// InMemoryCache is an in-memory implementation of the Cache interface. | ||
type InMemoryCache struct { | ||
data map[string]cacheItem | ||
mutex sync.RWMutex | ||
} | ||
|
||
// Ensure InMemoryCache implements the Cache interface. | ||
var _ Cache = (*InMemoryCache)(nil) | ||
|
||
// cacheItem represents an item stored in the cache. | ||
type cacheItem struct { | ||
data []byte | ||
expiration time.Time | ||
} | ||
|
||
// NewInMemoryCache creates a new instance of InMemoryCache. | ||
func NewInMemoryCache() *InMemoryCache { | ||
return &InMemoryCache{ | ||
data: make(map[string]cacheItem), | ||
} | ||
} | ||
|
||
// Set sets the value of a key in the cache. | ||
func (c *InMemoryCache) Set( | ||
ctx context.Context, | ||
key string, | ||
data []byte, | ||
expiration time.Duration, | ||
) error { | ||
c.mutex.Lock() | ||
defer c.mutex.Unlock() | ||
|
||
expiry := time.Now().Add(expiration) | ||
|
||
if expiration == 0 { | ||
// 100 years in the future to prevent expiry | ||
expiry = time.Now().AddDate(100, 0, 0) | ||
} | ||
|
||
c.data[key] = cacheItem{ | ||
data: data, | ||
expiration: expiry, | ||
} | ||
|
||
return nil | ||
} | ||
|
||
// Get retrieves the value of a key from the cache. | ||
func (c *InMemoryCache) Get(ctx context.Context, key string) ([]byte, error) { | ||
c.mutex.RLock() | ||
defer c.mutex.RUnlock() | ||
|
||
item, ok := c.data[key] | ||
if !ok || time.Now().After(item.expiration) { | ||
// Not a real ttl but just replicates it for fetching | ||
delete(c.data, key) | ||
|
||
return nil, ErrNotFound | ||
} | ||
|
||
return item.data, nil | ||
} | ||
|
||
// GetAll returns all the non-expired data in the cache. | ||
func (c *InMemoryCache) GetAll(ctx context.Context) map[string][]byte { | ||
c.mutex.RLock() | ||
defer c.mutex.RUnlock() | ||
|
||
result := make(map[string][]byte) | ||
|
||
for key, item := range c.data { | ||
if time.Now().After(item.expiration) { | ||
delete(c.data, key) | ||
} else { | ||
result[key] = item.data | ||
} | ||
} | ||
|
||
return result | ||
} | ||
|
||
// Delete removes a key from the cache. | ||
func (c *InMemoryCache) Delete(ctx context.Context, key string) error { | ||
c.mutex.Lock() | ||
defer c.mutex.Unlock() | ||
|
||
delete(c.data, key) | ||
return nil | ||
} | ||
|
||
func (c *InMemoryCache) Healthcheck(ctx context.Context) error { | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
package cache | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"time" | ||
|
||
"github.com/kava-labs/kava-proxy-service/logging" | ||
"github.com/redis/go-redis/v9" | ||
) | ||
|
||
type RedisConfig struct { | ||
Address string | ||
Password string | ||
DB int | ||
} | ||
|
||
// RedisCache is an implementation of Cache that uses Redis as the caching backend. | ||
type RedisCache struct { | ||
client *redis.Client | ||
*logging.ServiceLogger | ||
} | ||
|
||
var _ Cache = (*RedisCache)(nil) | ||
|
||
func NewRedisCache( | ||
cfg *RedisConfig, | ||
logger *logging.ServiceLogger, | ||
) (*RedisCache, error) { | ||
client := redis.NewClient(&redis.Options{ | ||
Addr: cfg.Address, | ||
Password: cfg.Password, | ||
DB: cfg.DB, | ||
}) | ||
|
||
return &RedisCache{ | ||
client: client, | ||
ServiceLogger: logger, | ||
}, nil | ||
} | ||
|
||
// Set sets the value for the given key in the cache with the given expiration. | ||
func (rc *RedisCache) Set( | ||
ctx context.Context, | ||
key string, | ||
value []byte, | ||
expiration time.Duration, | ||
) error { | ||
rc.Logger.Trace(). | ||
Str("key", key). | ||
Str("value", string(value)). | ||
Dur("expiration", expiration). | ||
Msg("setting value in redis") | ||
|
||
return rc.client.Set(ctx, key, value, expiration).Err() | ||
} | ||
|
||
// Get gets the value for the given key in the cache. | ||
func (rc *RedisCache) Get( | ||
ctx context.Context, | ||
key string, | ||
) ([]byte, error) { | ||
rc.Logger.Trace(). | ||
Str("key", key). | ||
Msg("getting value from redis") | ||
|
||
val, err := rc.client.Get(ctx, key).Bytes() | ||
if err == redis.Nil { | ||
rc.Logger.Trace(). | ||
Str("key", key). | ||
Msgf("value not found in redis") | ||
return nil, ErrNotFound | ||
} | ||
if err != nil { | ||
rc.Logger.Error(). | ||
Str("key", key). | ||
Err(err). | ||
Msg("error during getting value from redis") | ||
return nil, err | ||
} | ||
|
||
rc.Logger.Trace(). | ||
Str("key", key). | ||
Str("value", string(val)). | ||
Msg("successfully got value from redis") | ||
|
||
return val, nil | ||
} | ||
|
||
// Delete deletes the value for the given key in the cache. | ||
func (rc *RedisCache) Delete(ctx context.Context, key string) error { | ||
rc.Logger.Trace(). | ||
Str("key", key). | ||
Msg("deleting value from redis") | ||
|
||
return rc.client.Del(ctx, key).Err() | ||
} | ||
|
||
func (rc *RedisCache) Healthcheck(ctx context.Context) error { | ||
rc.Logger.Trace().Msg("redis healthcheck was called") | ||
|
||
// Check if we can connect to Redis | ||
_, err := rc.client.Ping(ctx).Result() | ||
if err != nil { | ||
rc.Logger.Error(). | ||
Err(err). | ||
Msg("can't ping redis") | ||
return fmt.Errorf("error connecting to Redis: %v", err) | ||
} | ||
|
||
rc.Logger.Trace().Msg("redis healthcheck was successful") | ||
|
||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.