processing_handler.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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. logResponse(reqID, 200, fmt.Sprintf("Processed in %s: %s; %+v", getTimerSince(ctx), getImageURL(ctx), po))
  66. }
  67. func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) {
  68. ctx := context.Background()
  69. if newRelicEnabled {
  70. var newRelicCancel context.CancelFunc
  71. ctx, newRelicCancel = startNewRelicTransaction(ctx, rw, r)
  72. defer newRelicCancel()
  73. }
  74. if prometheusEnabled {
  75. prometheusRequestsTotal.Inc()
  76. defer startPrometheusDuration(prometheusRequestDuration)()
  77. }
  78. processingSem <- struct{}{}
  79. defer func() { <-processingSem }()
  80. ctx, timeoutCancel := startTimer(ctx, time.Duration(conf.WriteTimeout)*time.Second)
  81. defer timeoutCancel()
  82. ctx, err := parsePath(ctx, r)
  83. if err != nil {
  84. panic(err)
  85. }
  86. ctx, downloadcancel, err := downloadImage(ctx)
  87. defer downloadcancel()
  88. if err != nil {
  89. if newRelicEnabled {
  90. sendErrorToNewRelic(ctx, err)
  91. }
  92. if prometheusEnabled {
  93. incrementPrometheusErrorsTotal("download")
  94. }
  95. panic(err)
  96. }
  97. checkTimeout(ctx)
  98. if conf.ETagEnabled {
  99. eTag := calcETag(ctx)
  100. rw.Header().Set("ETag", eTag)
  101. if eTag == r.Header.Get("If-None-Match") {
  102. logResponse(reqID, 304, "Not modified")
  103. rw.WriteHeader(304)
  104. return
  105. }
  106. }
  107. checkTimeout(ctx)
  108. imageData, processcancel, err := processImage(ctx)
  109. defer processcancel()
  110. if err != nil {
  111. if newRelicEnabled {
  112. sendErrorToNewRelic(ctx, err)
  113. }
  114. if prometheusEnabled {
  115. incrementPrometheusErrorsTotal("processing")
  116. }
  117. panic(err)
  118. }
  119. checkTimeout(ctx)
  120. respondWithImage(ctx, reqID, r, rw, imageData)
  121. }