timer.go 739 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. )
  7. var timerSinceCtxKey = ctxKey("timerSince")
  8. func startTimer(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc) {
  9. return context.WithTimeout(
  10. context.WithValue(ctx, timerSinceCtxKey, time.Now()),
  11. d,
  12. )
  13. }
  14. func getTimerSince(ctx context.Context) time.Duration {
  15. return time.Since(ctx.Value(timerSinceCtxKey).(time.Time))
  16. }
  17. func checkTimeout(ctx context.Context) {
  18. select {
  19. case <-ctx.Done():
  20. d := getTimerSince(ctx)
  21. if newRelicEnabled {
  22. sendTimeoutToNewRelic(ctx, d)
  23. }
  24. if prometheusEnabled {
  25. incrementPrometheusErrorsTotal("timeout")
  26. }
  27. panic(newError(503, fmt.Sprintf("Timeout after %v", d), "Timeout"))
  28. default:
  29. // Go ahead
  30. }
  31. }