in sandbox/ho11y/main.go [253:312]
func handler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
traceid := getXrayTraceID(trace.SpanFromContext(ctx))
// if enabled, we first handle throttling. if the current TPS value
// is larger than what user told us to, return a 429 and call it a day.
// we always need to increment the period counter for throttling:
if enableThrottling {
invokesInPeriod += 1
if tpsValue > tpsCutoffVal {
w.WriteHeader(http.StatusTooManyRequests)
invokeCounter.WithLabelValues(strconv.Itoa(http.StatusTooManyRequests)).Inc()
log.Info(fmt.Sprintf("Throttle engaged, got %v TPS with a %v TPS cutoff point", tpsValue, tpsCutoffVal))
return
}
}
// next, if failure injection is enabled, then we
// generate a random value (range: 0 to 100)
// and if this one is above a fixed threshold (50)
// then we drop the request with a randomly selected
// status code, bastard-operator-from-hell style.
// result: in average only half of the requests
// are successfully served:
if os.Getenv("HO11Y_INJECT_FAILURE") != "" {
threshold := 50
level := rand.Intn(100)
if level > threshold {
// now pick a random failure HTTP status code:
rc := responseCodes[rand.Intn(len(responseCodes))]
w.WriteHeader(rc)
invokeCounter.WithLabelValues(strconv.Itoa(rc)).Inc()
return
}
}
// if we are below the threshold, respond successfully
// that is with HTTP 200 status code:
w.Header().Set("Content-Type", "application/json")
// emit log event for invocation:
log.WithFields(
log.Fields{
"event": "invoke",
"traceID": traceid,
"remote": r.RemoteAddr,
},
).Info("ho11y was invoked")
// increment counter metric for invocation:
invokeCounter.WithLabelValues(strconv.Itoa(http.StatusOK)).Inc()
// emit trace(s) for invocation:
json := simplejson.New()
json.Set("traceId", traceid)
invokeDownstreams(ctx)
payload, _ := json.MarshalJSON()
_, _ = w.Write(payload)
}