Skip to content

Commit

Permalink
chg: improve score in bettercodehub
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiocicerchia committed Sep 17, 2021
1 parent c45a6bf commit bf0eec8
Show file tree
Hide file tree
Showing 10 changed files with 65 additions and 59 deletions.
4 changes: 2 additions & 2 deletions server/handler/etag.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func (rc RequestCall) GetResponseWithETag(ctx context.Context, proxy *httputil.R

// ETag wrapper doesn't work well with WebSocket and HTTP/2.
if wsutil.IsWebSocketRequest(&rc.Request) || rc.Request.ProtoMajor == HttpVersion2 {
telemetry.RegisterEvent(ctx, "request.etag.not_supported")
telemetry.From(ctx).RegisterEvent("request.etag.not_supported")
rc.GetLogger().Info("Current request doesn't support ETag.")

// Serve existing response.
Expand All @@ -36,7 +36,7 @@ func (rc RequestCall) GetResponseWithETag(ctx context.Context, proxy *httputil.R

// Serve existing response.
if rc.Response.MustServeOriginalResponse(ctx, &rc.Request) {
telemetry.RegisterEvent(ctx, "request.etag.serve_original")
telemetry.From(ctx).RegisterEvent("request.etag.serve_original")
rc.GetLogger().Info("Serving original response as cannot be handled with ETag.")

return false
Expand Down
4 changes: 2 additions & 2 deletions server/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func HandleRequest(res http.ResponseWriter, req *http.Request) {
defer tracingSpan.Finish()
ctx := opentracing.ContextWithSpan(context.Background(), tracingSpan)

telemetry.RegisterRequest(ctx, *req)
telemetry.From(ctx).RegisterRequest(*req)

rc, err := initRequestParams(ctx, res, req)
if err != nil {
Expand All @@ -44,7 +44,7 @@ func HandleRequest(res http.ResponseWriter, req *http.Request) {
return
}

telemetry.RegisterRequestCall(ctx, rc.ReqID, rc.GetRequestURL(), rc.GetScheme(), rc.IsWebSocket())
telemetry.From(ctx).RegisterRequestCall(rc.ReqID, rc.GetRequestURL(), rc.GetScheme(), rc.IsWebSocket())

if rc.Request.Method == http.MethodConnect {
if enableLoggingRequest {
Expand Down
2 changes: 1 addition & 1 deletion server/handler/healthcheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func HandleHealthcheck(cfg config.Configuration) func(res http.ResponseWriter, r
lwr.WriteHeader(statusCode)
_ = lwr.WriteBody("HTTP OK\n")

telemetry.RegisterStatusCode(ctx, statusCode)
telemetry.From(ctx).RegisterStatusCode(statusCode)

if redisOK {
_ = lwr.WriteBody("REDIS OK\n")
Expand Down
7 changes: 4 additions & 3 deletions server/handler/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func (rc RequestCall) HandleHTTPRequestAndProxy(ctx context.Context) {
cached = rc.serveCachedContent(ctx)
}

telemetry.RegisterRequestCacheStatus(ctx, forceFresh, enableCachedResponse, CacheStatusLabel[cached])
telemetry.From(ctx).RegisterRequestCacheStatus(forceFresh, enableCachedResponse, CacheStatusLabel[cached])

if cached == CacheStatusMiss {
rc.Response.Header().Set(response.CacheStatusHeader, response.CacheStatusHeaderMiss)
Expand Down Expand Up @@ -109,7 +109,8 @@ func (rc RequestCall) serveCachedContent(ctx context.Context) int {
rc.Response.Header().Set(response.CacheStatusHeader, response.CacheStatusHeaderHit)
}

telemetry.RegisterCacheStaleOrHit(ctx, uriObj.Stale, rc.Response.StatusCode)
telemetry.From(ctx).RegisterCacheStaleOrHit(uriObj.Stale)
telemetry.From(ctx).RegisterStatusCode(rc.Response.StatusCode)

transport.ServeCachedResponse(rc.Request.Context(), rc.Response, uriObj)

Expand All @@ -133,7 +134,7 @@ func (rc RequestCall) serveReverseProxyHTTP(ctx context.Context) {
rc.GetLogger().Debugf("Req URL: %s", rc.Request.URL.String())
rc.GetLogger().Debugf("Req Host: %s", rc.Request.Host)

telemetry.RegisterRequestUpstream(ctx, proxyURL, enableCachedResponse, CacheStatusLabel[CacheStatusMiss])
telemetry.From(ctx).RegisterRequestUpstream(proxyURL, enableCachedResponse, CacheStatusLabel[CacheStatusMiss])

proxy := httputil.NewSingleHostReverseProxy(&proxyURL)
proxy.Transport = rc.patchProxyTransport()
Expand Down
10 changes: 5 additions & 5 deletions server/handler/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func (rc RequestCall) IsLegitRequest(ctx context.Context, listeningPort string)
hostMatch := rc.DomainConfig.Server.Upstream.Host == rc.GetHostname()
legitPort := isLegitPort(rc.DomainConfig.Server.Port, listeningPort)

telemetry.RegisterLegitRequest(ctx, hostMatch, legitPort, rc.GetHostname(), listeningPort, rc.DomainConfig.Server.Upstream.Host, rc.DomainConfig.Server.Upstream.Port)
telemetry.From(ctx).RegisterLegitRequest(hostMatch, legitPort, rc.GetHostname(), listeningPort, rc.DomainConfig.Server.Upstream.Host, rc.DomainConfig.Server.Upstream.Port)

rc.GetLogger().Debugf("Is Hostname matching Request and Configuration? %v - Request: %s - Config: %s", hostMatch, rc.GetHostname(), rc.DomainConfig.Server.Upstream.Host)
rc.GetLogger().Debugf("Is Port matching Request and Configuration? %v - Request: %s - Config: %s", legitPort, listeningPort, rc.DomainConfig.Server.Port)
Expand Down Expand Up @@ -112,23 +112,23 @@ func (rc RequestCall) IsWebSocket() bool {
func (rc RequestCall) SendNotImplemented(ctx context.Context) {
rc.Response.SendNotImplemented()

telemetry.RegisterStatusCode(ctx, http.StatusNotImplemented)
telemetry.From(ctx).RegisterStatusCode(http.StatusNotImplemented)
}

func (rc RequestCall) SendMethodNotAllowed(ctx context.Context) {
rc.Response.ForceWriteHeader(http.StatusMethodNotAllowed)

telemetry.RegisterStatusCode(ctx, http.StatusMethodNotAllowed)
telemetry.From(ctx).RegisterStatusCode(http.StatusMethodNotAllowed)
}

func (rc RequestCall) SendNotModifiedResponse(ctx context.Context) {
rc.Response.SendNotModifiedResponse()

telemetry.RegisterStatusCode(ctx, http.StatusNotModified)
telemetry.From(ctx).RegisterStatusCode(http.StatusNotModified)
}

func (rc RequestCall) SendResponse(ctx context.Context) {
rc.Response.SendResponse()

telemetry.RegisterStatusCode(ctx, rc.Response.StatusCode)
telemetry.From(ctx).RegisterStatusCode(rc.Response.StatusCode)
}
5 changes: 3 additions & 2 deletions server/handler/purge.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,16 @@ func (rc RequestCall) HandlePurge(ctx context.Context) {

rc.GetLogger().Warnf("URL Not Purged %s: %v\n", rc.Request.URL.String(), err)

telemetry.RegisterPurge(ctx, status, http.StatusNotFound, err)
telemetry.From(ctx).RegisterPurge(status, err)
telemetry.From(ctx).RegisterStatusCode(http.StatusNotFound)

return
}

rc.Response.ForceWriteHeader(http.StatusOK)
_ = rc.Response.WriteBody("OK")

telemetry.RegisterPurge(ctx, status, http.StatusOK, nil)
telemetry.From(ctx).RegisterPurge(status, http.StatusOK, nil)

if enableLoggingRequest {
logger.LogRequest(rc.Request, *rc.Response, rc.ReqID, false, "-")
Expand Down
3 changes: 2 additions & 1 deletion server/handler/redirect.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,6 @@ func (rc RequestCall) RedirectToHTTPS(ctx context.Context) {
// Just write to client, no need to cache this response.
http.Redirect(rc.Response.ResponseWriter, &rc.Request, targetURL.String(), rc.DomainConfig.Server.Upstream.RedirectStatusCode)

telemetry.RegisterRedirect(ctx, targetURL, rc.DomainConfig.Server.Upstream.RedirectStatusCode)
telemetry.From(ctx).RegisterRedirect(targetURL)
telemetry.From(ctx).RegisterStatusCode(rc.DomainConfig.Server.Upstream.RedirectStatusCode)
}
2 changes: 1 addition & 1 deletion server/handler/ws.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func (rc RequestCall) serveReverseProxyWS(ctx context.Context) {
rc.GetLogger().Debugf("Req URL: %s", rc.Request.URL.String())
rc.GetLogger().Debugf("Req Host: %s", rc.Request.Host)

telemetry.RegisterRequestUpstream(ctx, proxyURL, enableCachedResponse, CacheStatusLabel[CacheStatusMiss])
telemetry.From(ctx).RegisterRequestUpstream(proxyURL, enableCachedResponse, CacheStatusLabel[CacheStatusMiss])

proxy := wsutil.NewSingleHostReverseProxy(&proxyURL)

Expand Down
2 changes: 1 addition & 1 deletion server/response/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ func (lwr *LoggedResponseWriter) SetETag(weak bool) {

// MustServeOriginalResponse - Check whether an ETag could be added.
func (lwr LoggedResponseWriter) MustServeOriginalResponse(ctx context.Context, req *http.Request) bool {
telemetry.RegisterServeOriginal(ctx, lwr.hash, lwr.ResponseWriter.Header(), lwr.StatusCode, len(lwr.Content))
telemetry.From(ctx).RegisterServeOriginal(lwr.hash, lwr.ResponseWriter.Header(), lwr.StatusCode, len(lwr.Content))

return lwr.hash == nil || // no hash has been computed (maybe no Write has been invoked)
lwr.ResponseWriter.Header().Get(headers.ETag) != "" || // there's already an ETag from upstream
Expand Down
85 changes: 44 additions & 41 deletions telemetry/telemetry.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,41 +9,45 @@ import (
"github.com/fabiocicerchia/go-proxy-cache/telemetry/metrics"
"github.com/fabiocicerchia/go-proxy-cache/telemetry/tracing"
"github.com/go-http-utils/headers"
"github.com/opentracing/opentracing-go"
)

func RegisterRedirect(ctx context.Context, targetURL url.URL, statusCode int) {
tracing.SpanFromContext(ctx).
SetTag(tracing.TagResponseLocation, targetURL.String()).
SetTag(tracing.TagResponseStatusCode, statusCode)
metrics.IncStatusCode(statusCode)
type TelemetryContext struct {
ctx context.Context
tracingSpan opentracing.Span
}

func RegisterHostHealth(healthy int, unhealthy int) {
metrics.SetHostHealthy(float64(healthy))
metrics.SetHostUnhealthy(float64(unhealthy))
func From(ctx context.Context) TelemetryContext {
return TelemetryContext{
ctx: ctx,
tracingSpan: tracing.SpanFromContext(ctx),
}
}

func (tc TelemetryContext) RegisterRedirect(targetURL url.URL) {
tc.tracingSpan.
SetTag(tracing.TagResponseLocation, targetURL.String())
}

func RegisterEvent(ctx context.Context, name string) {
tracing.AddEventsToSpan(tracing.SpanFromContext(ctx), name, map[string]string{})
func (tc TelemetryContext) RegisterEvent(name string) {
tracing.AddEventsToSpan(tc.tracingSpan, name, map[string]string{})
}

func RegisterRequest(ctx context.Context, req http.Request) {
func (tc TelemetryContext) RegisterRequest(req http.Request) {
metrics.IncRequestHost(req.Host)

tracing.SpanFromContext(ctx).
tc.tracingSpan.
SetTag(tracing.TagRequestHost, req.Host).
SetTag(tracing.TagRequestUrl, req.URL.String()).
SetTag(tracing.TagRequestMethod, req.Method)

metrics.IncHttpMethod(req.Method)
}

func RegisterRequestCall(ctx context.Context, reqID string, reqURL url.URL, scheme string, webSocket bool) {
tracingSpan := tracing.SpanFromContext(ctx)
func (tc TelemetryContext) RegisterRequestCall(reqID string, reqURL url.URL, scheme string, webSocket bool) {
tc.tracingSpan.SetBaggageItem(tracing.BaggageRequestID, reqID)

tracingSpan.SetBaggageItem(tracing.BaggageRequestID, reqID)

tracingSpan.
tc.tracingSpan.
SetTag(tracing.TagRequestId, reqID).
SetTag(tracing.TagRequestFullUrl, reqURL.String()).
SetTag(tracing.TagRequestScheme, scheme).
Expand All @@ -52,44 +56,42 @@ func RegisterRequestCall(ctx context.Context, reqID string, reqURL url.URL, sche
metrics.IncUrlScheme(scheme)
}

func RegisterStatusCode(ctx context.Context, statusCode int) {
tracing.SpanFromContext(ctx).
func (tc TelemetryContext) RegisterStatusCode(statusCode int) {
tc.tracingSpan.
SetTag(tracing.TagResponseStatusCode, statusCode)
metrics.IncStatusCode(statusCode)
}

func RegisterRequestCacheStatus(ctx context.Context, forceFresh bool, enableCachedResponse bool, cached string) {
tracing.SpanFromContext(ctx).
func (tc TelemetryContext) RegisterRequestCacheStatus(forceFresh bool, enableCachedResponse bool, cached string) {
tc.tracingSpan.
SetTag(tracing.TagCacheForcedFresh, forceFresh).
SetTag(tracing.TagCacheCacheable, enableCachedResponse).
SetTag(tracing.TagCacheCached, cached).
SetTag(tracing.TagCacheStale, cached == "STALE") // TODO: Magic value
}

func RegisterCacheStaleOrHit(ctx context.Context, stale bool, statusCode int) {
func (tc TelemetryContext) RegisterCacheStaleOrHit(stale bool) {
if stale {
metrics.IncCacheStale()
} else {
metrics.IncCacheHit()
}

tracing.SpanFromContext(ctx).
SetTag(tracing.TagCacheStale, stale).
SetTag(tracing.TagResponseStatusCode, statusCode)
metrics.IncStatusCode(statusCode)
tc.tracingSpan.
SetTag(tracing.TagCacheStale, stale)
}

func RegisterRequestUpstream(ctx context.Context, proxyURL url.URL, enableCachedResponse bool, cached string) {
tracing.SpanFromContext(ctx).
func (tc TelemetryContext) RegisterRequestUpstream(proxyURL url.URL, enableCachedResponse bool, cached string) {
tc.tracingSpan.
SetTag(tracing.TagProxyEndpoint, proxyURL.String()).
SetTag(tracing.TagCacheForcedFresh, false).
SetTag(tracing.TagCacheCacheable, enableCachedResponse).
SetTag(tracing.TagCacheCached, cached).
SetTag(tracing.TagCacheStale, false)
}

func RegisterLegitRequest(ctx context.Context, hostMatch bool, legitPort bool, hostname string, listeningPort string, confHostname string, confPort interface{}) {
tracing.SpanFromContext(ctx).
func (tc TelemetryContext) RegisterLegitRequest(hostMatch bool, legitPort bool, hostname string, listeningPort string, confHostname string, confPort interface{}) {
tc.tracingSpan.
SetTag(tracing.TagRequestIsLegitHostnameMatches, hostMatch).
SetTag(tracing.TagRequestIsLegitPortMatches, legitPort).
SetTag(tracing.TagRequestIsLegitRequestHostname, hostname).
Expand All @@ -98,24 +100,20 @@ func RegisterLegitRequest(ctx context.Context, hostMatch bool, legitPort bool, h
SetTag(tracing.TagRequestIsLegitConfPort, confPort)
}

func RegisterPurge(ctx context.Context, status bool, statusCode int, err error) {
tracingSpan := tracing.SpanFromContext(ctx)

tracingSpan.
SetTag(tracing.TagPurgeStatus, status).
SetTag(tracing.TagResponseStatusCode, statusCode)
metrics.IncStatusCode(statusCode)
func (tc TelemetryContext) RegisterPurge(status bool, err error) {
tc.tracingSpan.
SetTag(tracing.TagPurgeStatus, status)

if err != nil {
tracing.AddErrorToSpan(tracingSpan, err)
tracing.Fail(tracingSpan, "internal error")
tracing.AddErrorToSpan(tc.tracingSpan, err)
tracing.Fail(tc.tracingSpan, "internal error")

// TODO: Add tracing.Fail -> prometheus as failures
}
}

func RegisterServeOriginal(ctx context.Context, hash hash.Hash, header http.Header, statusCode int, lenContent int) {
tracing.SpanFromContext(ctx).
func (tc TelemetryContext) RegisterServeOriginal(hash hash.Hash, header http.Header, statusCode int, lenContent int) {
tc.tracingSpan.
SetTag(tracing.TagResponseMustServeOriginalResponseNoHashComputed, hash == nil).
SetTag(tracing.TagResponseMustServeOriginalResponseEtagPresent, header.Get(headers.ETag)).
SetTag(tracing.TagResponseMustServeOriginalResponseEtagAlreadyPresent, header.Get(headers.ETag) != "").
Expand All @@ -124,3 +122,8 @@ func RegisterServeOriginal(ctx context.Context, hash hash.Hash, header http.Head
SetTag(tracing.TagResponseMustServeOriginalResponseResponse204, statusCode == http.StatusNoContent).
SetTag(tracing.TagResponseMustServeOriginalResponseNoBufferedContent, lenContent == 0)
}

func RegisterHostHealth(healthy int, unhealthy int) {
metrics.SetHostHealthy(float64(healthy))
metrics.SetHostUnhealthy(float64(unhealthy))
}

0 comments on commit bf0eec8

Please sign in to comment.