processing_handler.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "time"
  9. )
  10. var (
  11. responseGzipBufPool *bufPool
  12. responseGzipPool *gzipPool
  13. processingSem chan struct{}
  14. headerVaryValue string
  15. )
  16. func initProcessingHandler() {
  17. processingSem = make(chan struct{}, conf.Concurrency)
  18. if conf.GZipCompression > 0 {
  19. responseGzipBufPool = newBufPool("gzip", conf.Concurrency, conf.GZipBufferSize)
  20. responseGzipPool = newGzipPool(conf.Concurrency)
  21. }
  22. vary := make([]string, 0)
  23. if conf.EnableWebpDetection || conf.EnforceWebp {
  24. vary = append(vary, "Accept")
  25. }
  26. if conf.GZipCompression > 0 {
  27. vary = append(vary, "Accept-Encoding")
  28. }
  29. if conf.EnableClientHints {
  30. vary = append(vary, "DPR", "Viewport-Width", "Width")
  31. }
  32. headerVaryValue = strings.Join(vary, ", ")
  33. }
  34. func respondWithImage(ctx context.Context, reqID string, r *http.Request, rw http.ResponseWriter, data []byte) {
  35. po := getProcessingOptions(ctx)
  36. var contentDisposition string
  37. if len(po.Filename) > 0 {
  38. contentDisposition = po.Format.ContentDisposition(po.Filename)
  39. } else {
  40. contentDisposition = po.Format.ContentDispositionFromURL(getImageURL(ctx))
  41. }
  42. rw.Header().Set("Expires", time.Now().Add(time.Second*time.Duration(conf.TTL)).Format(http.TimeFormat))
  43. rw.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, public", conf.TTL))
  44. rw.Header().Set("Content-Type", po.Format.Mime())
  45. rw.Header().Set("Content-Disposition", contentDisposition)
  46. if len(headerVaryValue) > 0 {
  47. rw.Header().Set("Vary", headerVaryValue)
  48. }
  49. if conf.GZipCompression > 0 && strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  50. buf := responseGzipBufPool.Get(0)
  51. defer responseGzipBufPool.Put(buf)
  52. gz := responseGzipPool.Get(buf)
  53. defer responseGzipPool.Put(gz)
  54. gz.Write(data)
  55. gz.Close()
  56. rw.Header().Set("Content-Encoding", "gzip")
  57. rw.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
  58. rw.WriteHeader(200)
  59. rw.Write(buf.Bytes())
  60. } else {
  61. rw.Header().Set("Content-Length", strconv.Itoa(len(data)))
  62. rw.WriteHeader(200)
  63. rw.Write(data)
  64. }
  65. imageURL := getImageURL(ctx)
  66. logResponse(reqID, r, 200, nil, &imageURL, po)
  67. // logResponse(reqID, r, 200, getTimerSince(ctx), getImageURL(ctx), po))
  68. }
  69. func respondWithNotModified(ctx context.Context, reqID string, r *http.Request, rw http.ResponseWriter) {
  70. rw.WriteHeader(304)
  71. imageURL := getImageURL(ctx)
  72. logResponse(reqID, r, 304, nil, &imageURL, getProcessingOptions(ctx))
  73. }
  74. func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) {
  75. ctx := r.Context()
  76. if newRelicEnabled {
  77. var newRelicCancel context.CancelFunc
  78. ctx, newRelicCancel = startNewRelicTransaction(ctx, rw, r)
  79. defer newRelicCancel()
  80. }
  81. if prometheusEnabled {
  82. prometheusRequestsTotal.Inc()
  83. defer startPrometheusDuration(prometheusRequestDuration)()
  84. }
  85. processingSem <- struct{}{}
  86. defer func() { <-processingSem }()
  87. ctx, timeoutCancel := context.WithTimeout(ctx, time.Duration(conf.WriteTimeout)*time.Second)
  88. defer timeoutCancel()
  89. ctx, err := parsePath(ctx, r)
  90. if err != nil {
  91. panic(err)
  92. }
  93. ctx, downloadcancel, err := downloadImage(ctx)
  94. defer downloadcancel()
  95. if err != nil {
  96. if newRelicEnabled {
  97. sendErrorToNewRelic(ctx, err)
  98. }
  99. if prometheusEnabled {
  100. incrementPrometheusErrorsTotal("download")
  101. }
  102. panic(err)
  103. }
  104. checkTimeout(ctx)
  105. if conf.ETagEnabled {
  106. eTag := calcETag(ctx)
  107. rw.Header().Set("ETag", eTag)
  108. if eTag == r.Header.Get("If-None-Match") {
  109. respondWithNotModified(ctx, reqID, r, rw)
  110. return
  111. }
  112. }
  113. checkTimeout(ctx)
  114. imageData, processcancel, err := processImage(ctx)
  115. defer processcancel()
  116. if err != nil {
  117. if newRelicEnabled {
  118. sendErrorToNewRelic(ctx, err)
  119. }
  120. if prometheusEnabled {
  121. incrementPrometheusErrorsTotal("processing")
  122. }
  123. panic(err)
  124. }
  125. checkTimeout(ctx)
  126. respondWithImage(ctx, reqID, r, rw, imageData)
  127. }