Skip to content

Commit

Permalink
caches: support Redis backend
Browse files Browse the repository at this point in the history
  • Loading branch information
mathstuf committed Jun 24, 2022
1 parent 9c9355b commit 7aaf1d2
Show file tree
Hide file tree
Showing 4 changed files with 177 additions and 1 deletion.
108 changes: 108 additions & 0 deletions caches/redis.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package caches

import (
"context"
"encoding/hex"
"errors"
"github.com/go-redis/redis/v8"
"os"
"strconv"
)

type RedisConfiguration struct {
Address string `json:"address"`
Password string `json:"password"`
Database int `json:"database"`
}

type RedisCache struct {
ctx context.Context
client *redis.Client
}

func getRedisAddr() (string, error) {
addr := os.Getenv("CLANG_TIDY_CACHE_REDIS_ADDRESS")
if addr == "" {
return "", errors.New("`CLANG_TIDY_CACHE_REDIS` must be set")
}

return addr, nil
}

func getRedisPassword() string {
return os.Getenv("CLANG_TIDY_CACHE_REDIS_PASSWORD")
}

func getRedisDatabase() int {
db_str := os.Getenv("CLANG_TIDY_CACHE_REDIS_DATABASE")
if db_str == "" {
return 0
}

db, err := strconv.Atoi(db_str)
if err == nil {
db = 0
}

return db
}

func NewRedisCache(cfg *RedisConfiguration) (*RedisCache, error) {
var addr string
if cfg.Address == "" {
var err error
addr, err = getRedisAddr()

if err != nil {
return nil, err
}
} else {
addr = cfg.Address
}

var pw string
if cfg.Password == "" {
pw = getRedisPassword()
} else {
pw = cfg.Password
}

db := cfg.Database

client := redis.NewClient(&redis.Options{
Addr: addr,
Password: pw,
DB: db,
})

ctx := context.Background()

_, err := client.Ping(ctx).Result()
if err != nil {
return nil, err
}

cache := RedisCache {
ctx: ctx,
client: client,
}

return &cache, nil
}

func (c *RedisCache) FindEntry(digest []byte) ([]byte, error) {
objectName := hex.EncodeToString(digest)

data, err := c.client.Get(c.ctx, objectName).Bytes()
if err != nil {
return nil, err
}

return data, err
}

func (c *RedisCache) SaveEntry(digest []byte, content []byte) error {
objectName := hex.EncodeToString(digest)

return c.client.Set(c.ctx, objectName, content, 0).Err()
}
5 changes: 4 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,7 @@ module github.com/ejfitzgerald/clang-tidy-cache

go 1.15

require cloud.google.com/go/storage v1.14.0
require (
cloud.google.com/go/storage v1.14.0
github.com/go-redis/redis/v8 v8.11.5
)
Loading

0 comments on commit 7aaf1d2

Please sign in to comment.