Skip to content

Commit

Permalink
Temporary commit
Browse files Browse the repository at this point in the history
  • Loading branch information
evgeniy-scherbina committed Oct 12, 2023
1 parent 428d5b7 commit a3f9718
Showing 3 changed files with 41 additions and 25 deletions.
54 changes: 30 additions & 24 deletions service/cachemdw/middleware.go
Original file line number Diff line number Diff line change
@@ -3,16 +3,14 @@ package cachemdw
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"

"github.com/kava-labs/kava-proxy-service/clients/cache"
"github.com/kava-labs/kava-proxy-service/decode"
"net/http"
)

const (
CachedContextKey = "X-KAVA-PROXY-CACHED"
IsCachedContextKey = "X-KAVA-PROXY-IS-CACHED"
ResponseContextKey = "X-KAVA-PROXY-RESPONSE"

CacheHeaderKey = "X-KAVA-PROXY-CACHE-STATUS"
CacheHitHeaderValue = "HIT"
@@ -29,7 +27,7 @@ func (c *ServiceCache) Middleware(
next http.Handler,
) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
uncachedContext := context.WithValue(r.Context(), CachedContextKey, false)
uncachedContext := context.WithValue(r.Context(), IsCachedContextKey, false)

// Skip caching if we can't get decoded request
req := r.Context().Value(c.decodedRequestContextKey)
@@ -85,7 +83,7 @@ func (c *ServiceCache) respondFromCache(
c.Logger.Error().Msg(fmt.Sprintf("can't write cached response: %v", err))
}

cachedContext := context.WithValue(r.Context(), CachedContextKey, true)
cachedContext := context.WithValue(r.Context(), IsCachedContextKey, true)
next.ServeHTTP(w, r.WithContext(cachedContext))
}

@@ -98,34 +96,42 @@ func (c *ServiceCache) respondAndCache(
) {
w.Header().Add(CacheHeaderKey, CacheMissHeaderValue)

recorder := httptest.NewRecorder()
next.ServeHTTP(recorder, r.WithContext(uncachedContext))
result := recorder.Result()
c.Logger.Error().Msgf("RESPOND_AND_CACHE: %T, %v", next, next)

if result.StatusCode != http.StatusOK {
return
}
//recorder := httptest.NewRecorder()
next.ServeHTTP(w, r.WithContext(uncachedContext))
//result := recorder.Result()

body := recorder.Body.Bytes()
for k, v := range result.Header {
w.Header().Set(k, strings.Join(v, ","))
}
w.WriteHeader(result.StatusCode)
_, err := w.Write(body)
if err != nil {
c.Logger.Error().Msg(fmt.Sprintf("can't write response: %v", err))
}
//if result.StatusCode != http.StatusOK {
// return
//}

//body := recorder.Body.Bytes()
//for k, v := range result.Header {
// w.Header().Set(k, strings.Join(v, ","))
//}
//w.WriteHeader(result.StatusCode)
//_, err := w.Write(body)
//if err != nil {
// c.Logger.Error().Msg(fmt.Sprintf("can't write response: %v", err))
//}

c.Logger.Error().Msg("RESPOND_AND_CACHE")

response := r.Context().Value(ResponseContextKey)
responseBytes := response.([]byte)

if err := c.ValidateAndCacheQueryResponse(
r.Context(),
decodedReq,
body,
//body,
responseBytes,
); err != nil {
c.Logger.Error().Msg(fmt.Sprintf("can't validate and cache response: %v", err))
}
}

func IsRequestCached(ctx context.Context) bool {
cached, ok := ctx.Value(CachedContextKey).(bool)
cached, ok := ctx.Value(IsCachedContextKey).(bool)
return ok && cached
}
2 changes: 2 additions & 0 deletions service/cachemdw/middleware_test.go
Original file line number Diff line number Diff line change
@@ -30,6 +30,8 @@ func TestE2ETestServiceCacheMiddleware(t *testing.T) {
if !cachemdw.IsRequestCached(r.Context()) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(testEVMQueries[TestRequestEthBlockByNumberSpecific].ResponseBody))

responseContext := context.WithValue(requestHostnameContext, cachemdw.ResponseContextKey, lrw.body)
}
})

10 changes: 9 additions & 1 deletion service/middleware.go
Original file line number Diff line number Diff line change
@@ -149,6 +149,8 @@ func createRequestLoggingMiddleware(h http.HandlerFunc, serviceLogger *logging.S
// all afterRequestInterceptors will be iterated (in slice order)
// through and executed before the response is written to the caller
func createProxyRequestMiddleware(next http.Handler, config config.Config, serviceLogger *logging.ServiceLogger, beforeRequestInterceptors []RequestInterceptor, afterRequestInterceptors []RequestInterceptor) http.HandlerFunc {
serviceLogger.Logger.Error().Msg("CREATE_PROXY_REQUEST_MIDDLEWARE")

// create an http handler that will proxy any request to the specified URL
reverseProxyForHost := make(map[string]*httputil.ReverseProxy)

@@ -162,6 +164,8 @@ func createProxyRequestMiddleware(next http.Handler, config config.Config, servi

handler := func(proxies map[string]*httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
serviceLogger.Logger.Error().Msg("CREATE_PROXY_REQUEST_MIDDLEWARE")

serviceLogger.Trace().Msg(fmt.Sprintf("proxying request %+v", r))

proxyRequestAt := time.Now()
@@ -247,7 +251,11 @@ func createProxyRequestMiddleware(next http.Handler, config config.Config, servi
// extract the original hostname the request was sent to
requestHostnameContext := context.WithValue(originRoundtripLatencyContext, RequestHostnameContextKey, r.Host)

enrichedContext := requestHostnameContext
responseContext := context.WithValue(requestHostnameContext, cachemdw.ResponseContextKey, lrw.body)

serviceLogger.Logger.Error().Msg("ENRICHED_CONTEXT")

enrichedContext := responseContext

// parse the remote address of the request for use below
remoteAddressParts := strings.Split(r.RemoteAddr, ":")

0 comments on commit a3f9718

Please sign in to comment.