queuing.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package internal
  2. import (
  3. "net/http"
  4. "strconv"
  5. "strings"
  6. "time"
  7. )
  8. const (
  9. xRequestStart = "X-Request-Start"
  10. xQueueStart = "X-Queue-Start"
  11. )
  12. var (
  13. earliestAcceptableSeconds = time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC).Unix()
  14. latestAcceptableSeconds = time.Date(2050, time.January, 1, 0, 0, 0, 0, time.UTC).Unix()
  15. )
  16. func checkQueueTimeSeconds(secondsFloat float64) time.Time {
  17. seconds := int64(secondsFloat)
  18. nanos := int64((secondsFloat - float64(seconds)) * (1000.0 * 1000.0 * 1000.0))
  19. if seconds > earliestAcceptableSeconds && seconds < latestAcceptableSeconds {
  20. return time.Unix(seconds, nanos)
  21. }
  22. return time.Time{}
  23. }
  24. func parseQueueTime(s string) time.Time {
  25. f, err := strconv.ParseFloat(s, 64)
  26. if nil != err {
  27. return time.Time{}
  28. }
  29. if f <= 0 {
  30. return time.Time{}
  31. }
  32. // try microseconds
  33. if t := checkQueueTimeSeconds(f / (1000.0 * 1000.0)); !t.IsZero() {
  34. return t
  35. }
  36. // try milliseconds
  37. if t := checkQueueTimeSeconds(f / (1000.0)); !t.IsZero() {
  38. return t
  39. }
  40. // try seconds
  41. if t := checkQueueTimeSeconds(f); !t.IsZero() {
  42. return t
  43. }
  44. return time.Time{}
  45. }
  46. // QueueDuration TODO
  47. func QueueDuration(hdr http.Header, txnStart time.Time) time.Duration {
  48. s := hdr.Get(xQueueStart)
  49. if "" == s {
  50. s = hdr.Get(xRequestStart)
  51. }
  52. if "" == s {
  53. return 0
  54. }
  55. s = strings.TrimPrefix(s, "t=")
  56. qt := parseQueueTime(s)
  57. if qt.IsZero() {
  58. return 0
  59. }
  60. if qt.After(txnStart) {
  61. return 0
  62. }
  63. return txnStart.Sub(qt)
  64. }