Rebuild of cache module #3

Merged
keedosn merged 1 commits from develop-issue-2 into develop 2021-07-24 18:23:09 +02:00
9 changed files with 235 additions and 97 deletions
Showing only changes of commit a0f162b91c - Show all commits

View File

@ -13,4 +13,6 @@ type CacheDatastore interface {
SetKey(string, interface{}, int) error SetKey(string, interface{}, int) error
GetKey(string) (interface{}, error) GetKey(string) (interface{}, error)
IsConnected() bool
} }

42
pkg/cache/memory_datastore.go vendored Normal file
View File

@ -0,0 +1,42 @@
// ___ ____ ___ ___
// \ \ / / | _ | __| \ \ / / || | __ || || _ |
// \ \/ / |___ | |__ \ \/ / || |___ || ||___|
// \ / | _ | _ | \ / || __ | || ||\\
// \/ |___ |___ | \/ || ____| || || \\
//
// Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License
// Repo: https://git.pbiernat.dev/golang/vegvisir
package cache
import (
"errors"
)
func NewMemoryDatastore() *MemoryDatastore {
return &MemoryDatastore{
cache: make(map[string]interface{}),
}
}
type MemoryDatastore struct {
cache map[string]interface{}
}
func (ds *MemoryDatastore) SetKey(key string, data interface{}, ttl int) error {
ds.cache[key] = data
return nil
}
func (ds *MemoryDatastore) GetKey(key string) (interface{}, error) {
if data, ok := ds.cache[key]; ok {
return data, nil
}
return nil, errors.New("Key not found" + key)
}
func (ds *MemoryDatastore) IsConnected() bool {
return true
}

View File

@ -23,13 +23,11 @@ func NewRedisDatastore(host string, port int) *RedisDatastore {
Password: "", // FIXME: use env or param Password: "", // FIXME: use env or param
DB: 0, // FIXME: use env or param DB: 0, // FIXME: use env or param
}), }),
cache: make(map[string]interface{}),
} }
} }
type RedisDatastore struct { type RedisDatastore struct {
client *redis.Client client *redis.Client
cache map[string]interface{}
} }
func (ds *RedisDatastore) SetKey(key string, data interface{}, ttl int) error { func (ds *RedisDatastore) SetKey(key string, data interface{}, ttl int) error {
@ -38,16 +36,10 @@ func (ds *RedisDatastore) SetKey(key string, data interface{}, ttl int) error {
return err return err
} }
// ds.cache[key] = data
return nil return nil
} }
func (ds *RedisDatastore) GetKey(key string) (interface{}, error) { func (ds *RedisDatastore) GetKey(key string) (interface{}, error) {
// if data, ok := ds.cache[key]; ok {
// return data, nil
// }
data, err := ds.client.Get(key).Result() data, err := ds.client.Get(key).Result()
if err != nil { if err != nil {
return nil, err return nil, err
@ -55,3 +47,9 @@ func (ds *RedisDatastore) GetKey(key string) (interface{}, error) {
return data, nil return data, nil
} }
func (ds *RedisDatastore) IsConnected() bool {
_, err := ds.client.Ping().Result()
return err == nil
}

24
pkg/cache/response.go vendored
View File

@ -34,22 +34,35 @@ func NewResponseCacheManager(datastore CacheDatastore, ttl int) ResponseCacheMan
} }
} }
func (rm *ResponseCacheManager) Save(name string, r ResponseCache) { func (rm *ResponseCacheManager) Save(name string, r ResponseCache) bool {
if !rm.datastore.IsConnected() {
log.Println("Response-cache:", "Not connected to server")
return false
}
data, err := json.Marshal(r) data, err := json.Marshal(r)
if err != nil { if err != nil {
log.Println("JSON:", err) // FIXME log.Println("Response-cache", "JSON encode:", err)
return false
} }
name = rm.prefix + name name = rm.prefix + name
err = rm.datastore.SetKey(name, string(data), rm.ttl) err = rm.datastore.SetKey(name, string(data), rm.ttl)
if err != nil { if err != nil {
log.Println("REDIS:", err, name) // FIXME log.Println("Response-cache:", err, name) // FIXME
return false
} }
return true
} }
func (rm *ResponseCacheManager) Load(name string) (bool, *ResponseCache) { func (rm *ResponseCacheManager) Load(name string) (bool, *ResponseCache) {
name = rm.prefix + name if !rm.datastore.IsConnected() {
log.Println("Response-cache:", "Not connected to server")
return false, &ResponseCache{}
}
name = rm.prefix + name
data, err := rm.datastore.GetKey(name) data, err := rm.datastore.GetKey(name)
if err != nil { if err != nil {
return false, &ResponseCache{} return false, &ResponseCache{}
@ -58,7 +71,8 @@ func (rm *ResponseCacheManager) Load(name string) (bool, *ResponseCache) {
rc := &ResponseCache{} rc := &ResponseCache{}
err = json.Unmarshal([]byte(data.(string)), &rc) err = json.Unmarshal([]byte(data.(string)), &rc)
if err != nil { if err != nil {
log.Println("JSON:", err) // FIXME log.Println("Response-cache:", "JSON docode:", err)
return false, &ResponseCache{}
} }
return true, rc return true, rc

40
pkg/cache/route.go vendored
View File

@ -21,42 +21,58 @@ type RouteCache struct {
type RouteCacheManager struct { type RouteCacheManager struct {
datastore CacheDatastore datastore CacheDatastore
prefix string
ttl int ttl int
} }
func NewRouteCacheManager(datastore CacheDatastore, ttl int) RouteCacheManager { func NewRouteCacheManager(datastore CacheDatastore, ttl int) RouteCacheManager {
return RouteCacheManager{ return RouteCacheManager{
datastore: datastore, datastore: datastore,
prefix: "route_",
ttl: ttl, ttl: ttl,
} }
} }
func (rm *RouteCacheManager) Save(name string, r RouteCache) { func (rm *RouteCacheManager) Save(name string, r RouteCache) bool {
if !rm.datastore.IsConnected() {
log.Println("Route-cache:", "Not connected to server")
return false
}
data, err := json.Marshal(r) data, err := json.Marshal(r)
if err != nil { if err != nil {
log.Println("JSON:", err) // FIXME log.Println("Route-cache", "JSON encode:", err)
return false
} }
err = rm.datastore.SetKey("route_"+name, data, rm.ttl) name = rm.prefix + name
err = rm.datastore.SetKey(name, data, rm.ttl)
if err != nil { if err != nil {
log.Println("REDIS:", err, name) // FIXME log.Println("Route-cache:", "Unable to save", name, err)
} return false
} }
func (rm *RouteCacheManager) Load(name string) (bool, RouteCache) { return true
name = "route_" + name }
func (rm *RouteCacheManager) Load(name string) (bool, *RouteCache) {
if !rm.datastore.IsConnected() {
log.Println("Route-cache:", "Not connected to server")
return false, &RouteCache{}
}
name = rm.prefix + name
data, err := rm.datastore.GetKey(name) data, err := rm.datastore.GetKey(name)
if err != nil { if err != nil {
log.Println("REDIS:", err, name) // FIXME log.Println("Route-cache:", "Unable to load", name, err)
return false, &RouteCache{}
return false, RouteCache{}
} }
rc := RouteCache{} rc := &RouteCache{}
err = json.Unmarshal([]byte(data.(string)), &rc) err = json.Unmarshal([]byte(data.(string)), &rc)
if err != nil { if err != nil {
log.Println("JSON:", err) // FIXME log.Println("Route-cache:", "JSON decode:", err)
return false, &RouteCache{}
} }
return true, rc return true, rc

View File

@ -18,6 +18,8 @@ import (
type Config struct { type Config struct {
Server Server Server Server
Backends map[string]Backend Backends map[string]Backend
confPath string
} }
type Server struct { type Server struct {
@ -42,12 +44,18 @@ var DefaultRoute = Route{
Target: "", Target: "",
} }
func (c *Config) Load(cPath string) error { func New(confPath string) *Config {
if _, err := os.Stat(cPath); err != nil { return &Config{
confPath: confPath,
}
}
func (c *Config) Load() error {
if _, err := os.Stat(c.confPath); err != nil {
return err return err
} }
data, err := ioutil.ReadFile(cPath) data, err := ioutil.ReadFile(c.confPath)
if err != nil { if err != nil {
return err return err
} }

10
pkg/server/response.go Normal file
View File

@ -0,0 +1,10 @@
// ___ ____ ___ ___
// \ \ / / | _ | __| \ \ / / || | __ || || _ |
// \ \/ / |___ | |__ \ \/ / || |___ || ||___|
// \ / | _ | _ | \ / || __ | || ||\\
// \/ |___ |___ | \/ || ____| || || \\
//
// Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License
// Repo: https://git.pbiernat.dev/golang/vegvisir
package server

83
pkg/server/router.go Normal file
View File

@ -0,0 +1,83 @@
// ___ ____ ___ ___
// \ \ / / | _ | __| \ \ / / || | __ || || _ |
// \ \/ / |___ | |__ \ \/ / || |___ || ||___|
// \ / | _ | _ | \ / || __ | || ||\\
// \/ |___ |___ | \/ || ____| || || \\
//
// Copyright (c) 2021 Piotr Biernat. https://pbiernat.dev. MIT License
// Repo: https://git.pbiernat.dev/golang/vegvisir
package server
import (
"fmt"
"regexp"
"strings"
"vegvisir/pkg/cache"
"vegvisir/pkg/config"
)
type Router struct {
config *config.Config
rcm cache.RouteCacheManager // Redis cache
rCache map[string]cache.RouteCache // Internal route cache - TMP?
}
type Route struct {
SourceUrl string
TargetUrl string
}
func NewRouter(conf *config.Config, cacheDS cache.CacheDatastore, ttl int) *Router {
return &Router{
config: conf,
rcm: cache.NewRouteCacheManager(cacheDS, ttl),
rCache: make(map[string]cache.RouteCache),
}
}
func (r *Router) FindByRequestURL(url []byte) (bool, Route) {
var sUrl string = string(url)
for bId := range r.config.Backends {
bck := r.config.Backends[bId]
if !strings.Contains(sUrl, bck.PrefixUrl) {
continue
}
for rId := range bck.Routes {
routeCfg := &bck.Routes[rId]
// if ok, cRoute := s.rCacheManager.Load(sUri); ok {
// return true, cRoute
// }
if cRoute, ok := r.rCache[sUrl]; ok {
route := Route{
SourceUrl: cRoute.SourceUrl,
TargetUrl: cRoute.TargetUrl,
}
return true, route
}
rgxp := regexp.MustCompile(fmt.Sprintf("%s%s", bck.PrefixUrl, routeCfg.Pattern))
if rgxp.Match(url) {
targetUrl := bck.BackendAddress + rgxp.ReplaceAllString(sUrl, routeCfg.Target)
route := Route{
SourceUrl: sUrl,
TargetUrl: targetUrl,
}
// s.rCacheManager.Save(sUri, cRoute)
r.rCache[sUrl] = cache.RouteCache{
SourceUrl: route.SourceUrl,
TargetUrl: route.TargetUrl,
}
return true, route
}
}
}
return false, Route{}
}

View File

@ -15,8 +15,6 @@ import (
"log" "log"
"os" "os"
"os/signal" "os/signal"
"regexp"
"strings"
"time" "time"
"vegvisir/pkg/cache" "vegvisir/pkg/cache"
"vegvisir/pkg/config" "vegvisir/pkg/config"
@ -30,32 +28,40 @@ const (
) )
type Server struct { type Server struct {
Config config.Config config *config.Config
router *Router
cFilePath string
rCache map[string]cache.RouteCache // Internal route cache
routeCM cache.RouteCacheManager // Redis route cache
respCM cache.ResponseCacheManager // Redis response cache respCM cache.ResponseCacheManager // Redis response cache
} }
func NewServer(cPath string) *Server { func NewServer(cPath string) *Server {
datastore := cache.NewRedisDatastore("127.0.0.7", 6379) // FIXME use config or env... config := config.New(cPath)
return &Server{ if err := config.Load(); err != nil {
cFilePath: cPath, log.Fatalln("Unable to find config file: ", cPath, err)
rCache: make(map[string]cache.RouteCache),
routeCM: cache.NewRouteCacheManager(datastore, 30), //FIXME use ttl(seconds) from config or env...
respCM: cache.NewResponseCacheManager(datastore, 30), //FIXME use ttl(seconds) from config or env...
} }
server := &Server{
config: config,
}
redisDS := cache.NewRedisDatastore("127.0.0.1", 6379) // FIXME use config or env...
if !redisDS.IsConnected() {
log.Println("Redis server not responding, switching to memory cache...")
memDS := cache.NewMemoryDatastore()
server.router = NewRouter(config, memDS, 30) //FIXME for memory datasource ttl is useles right now...
server.respCM = cache.NewResponseCacheManager(memDS, 30) //FIXME for memory datasource ttl is useles right now...
} else {
server.router = NewRouter(config, redisDS, 30) //FIXME use ttl(seconds) from config or env...
server.respCM = cache.NewResponseCacheManager(redisDS, 30) //FIXME use ttl(seconds) from config or env...
}
return server
} }
func (s *Server) Run() { func (s *Server) Run() {
if err := s.Config.Load(s.cFilePath); err != nil {
log.Fatalln("Unable to find config file: ", s.cFilePath, err)
}
go func() { go func() {
serverAddress := s.Config.Server.Address + ":" + fmt.Sprint(s.Config.Server.Port) serverAddress := s.config.Server.Address + ":" + fmt.Sprint(s.config.Server.Port)
if err := fasthttp.ListenAndServe(serverAddress, s.mainHandler); err != nil { if err := fasthttp.ListenAndServe(serverAddress, s.mainHandler); err != nil {
log.Fatalf("Server panic! Error message: %s", err) log.Fatalf("Server panic! Error message: %s", err)
} }
@ -86,10 +92,10 @@ func (s *Server) mainHandler(ctx *fasthttp.RequestCtx) {
ctx.Response.Header.Add(fasthttp.HeaderServer, Name) ctx.Response.Header.Add(fasthttp.HeaderServer, Name)
// move all below logic to concrete handler or sth.... // move all below logic to concrete handler or sth....
reqUri, sReqUri, sReqMethod := ctx.RequestURI(), string(ctx.RequestURI()), string(ctx.Method()) reqUrl, sReqUrl, sReqMethod := ctx.RequestURI(), string(ctx.RequestURI()), string(ctx.Method())
log.Println("Incomming request:", sReqMethod, sReqUri) log.Println("Incomming request:", sReqMethod, sReqUrl)
found, route := s.findRouteByRequestURI(reqUri) found, route := s.router.FindByRequestURL(reqUrl)
if !found { if !found {
// FIXME: return 404/5xx error in repsonse, maybe define it in Backend config? // FIXME: return 404/5xx error in repsonse, maybe define it in Backend config?
ctx.SetStatusCode(fasthttp.StatusNotFound) ctx.SetStatusCode(fasthttp.StatusNotFound)
@ -97,10 +103,10 @@ func (s *Server) mainHandler(ctx *fasthttp.RequestCtx) {
} }
// handle response caching // handle response caching
if ok, data := s.respCM.Load(sReqUri); ok { if ok, data := s.respCM.Load(sReqUrl); ok {
log.Println("Read resp from cache: ", route.TargetUrl) log.Println("Read resp from cache: ", route.TargetUrl)
ctx.SetBody([]byte(data.Body)) ctx.SetBody([]byte(data.Body)) // FIXME missing headers etc...
} else { } else {
log.Println("Send req to backend url: ", route.TargetUrl) log.Println("Send req to backend url: ", route.TargetUrl)
@ -126,51 +132,10 @@ func (s *Server) mainHandler(ctx *fasthttp.RequestCtx) {
// save response to cache // save response to cache
respCache := cache.ResponseCache{ respCache := cache.ResponseCache{
URL: sReqUri, URL: sReqUrl,
Body: string(bckResp.Body()), Body: string(bckResp.Body()),
// Headers: [] // Headers: []
} // FIXME: prepare resp cache struct in respCM.Save method or other service... } // FIXME: prepare resp cache struct in respCM.Save method or other service...
s.respCM.Save(sReqUri, respCache) s.respCM.Save(sReqUrl, respCache)
} }
} }
func (s *Server) findRouteByRequestURI(uri []byte) (bool, cache.RouteCache) {
var sUri string = string(uri)
for bId := range s.Config.Backends {
bck := s.Config.Backends[bId]
if !strings.Contains(sUri, bck.PrefixUrl) {
continue
}
for rId := range bck.Routes {
route := &bck.Routes[rId]
// if ok, cRoute := s.rCacheManager.Load(sUri); ok {
// return true, cRoute
// }
if cRoute, ok := s.rCache[sUri]; ok {
return true, cRoute
}
rgxp := regexp.MustCompile(fmt.Sprintf("%s%s", bck.PrefixUrl, route.Pattern))
if rgxp.Match(uri) {
targetUrl := bck.BackendAddress + rgxp.ReplaceAllString(sUri, route.Target)
cRoute := cache.RouteCache{ // FIXME: data duplication and use short alias for backend and route!
// Backend: bck,
// Route: *route,
SourceUrl: sUri,
TargetUrl: targetUrl,
}
// s.rCacheManager.Save(sUri, cRoute)
s.rCache[sUri] = cRoute
return true, cRoute
}
}
}
return false, cache.RouteCache{}
}