processing_handler.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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("Content-Type", po.Format.Mime())
  43. rw.Header().Set("Content-Disposition", contentDisposition)
  44. var cacheControl, expires string
  45. if conf.CacheControlPassthrough {
  46. cacheControl = getCacheControlHeader(ctx)
  47. expires = getExpiresHeader(ctx)
  48. }
  49. if len(cacheControl) == 0 && len(expires) == 0 {
  50. cacheControl = fmt.Sprintf("max-age=%d, public", conf.TTL)
  51. expires = time.Now().Add(time.Second * time.Duration(conf.TTL)).Format(http.TimeFormat)
  52. }
  53. if len(cacheControl) > 0 {
  54. rw.Header().Set("Cache-Control", cacheControl)
  55. }
  56. if len(expires) > 0 {
  57. rw.Header().Set("Expires", expires)
  58. }
  59. if len(headerVaryValue) > 0 {
  60. rw.Header().Set("Vary", headerVaryValue)
  61. }
  62. if conf.GZipCompression > 0 && strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  63. buf := responseGzipBufPool.Get(0)
  64. defer responseGzipBufPool.Put(buf)
  65. gz := responseGzipPool.Get(buf)
  66. defer responseGzipPool.Put(gz)
  67. gz.Write(data)
  68. gz.Close()
  69. rw.Header().Set("Content-Encoding", "gzip")
  70. rw.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
  71. rw.WriteHeader(200)
  72. rw.Write(buf.Bytes())
  73. } else {
  74. rw.Header().Set("Content-Length", strconv.Itoa(len(data)))
  75. rw.WriteHeader(200)
  76. rw.Write(data)
  77. }
  78. imageURL := getImageURL(ctx)
  79. logResponse(reqID, r, 200, nil, &imageURL, po)
  80. // logResponse(reqID, r, 200, getTimerSince(ctx), getImageURL(ctx), po))
  81. }
  82. func respondWithNotModified(ctx context.Context, reqID string, r *http.Request, rw http.ResponseWriter) {
  83. rw.WriteHeader(304)
  84. imageURL := getImageURL(ctx)
  85. logResponse(reqID, r, 304, nil, &imageURL, getProcessingOptions(ctx))
  86. }
  87. func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) {
  88. ctx := r.Context()
  89. if newRelicEnabled {
  90. var newRelicCancel context.CancelFunc
  91. ctx, newRelicCancel = startNewRelicTransaction(ctx, rw, r)
  92. defer newRelicCancel()
  93. }
  94. if prometheusEnabled {
  95. prometheusRequestsTotal.Inc()
  96. defer startPrometheusDuration(prometheusRequestDuration)()
  97. }
  98. processingSem <- struct{}{}
  99. defer func() { <-processingSem }()
  100. ctx, timeoutCancel := context.WithTimeout(ctx, time.Duration(conf.WriteTimeout)*time.Second)
  101. defer timeoutCancel()
  102. ctx, err := parsePath(ctx, r)
  103. if err != nil {
  104. panic(err)
  105. }
  106. ctx, downloadcancel, err := downloadImage(ctx)
  107. defer downloadcancel()
  108. if err != nil {
  109. if newRelicEnabled {
  110. sendErrorToNewRelic(ctx, err)
  111. }
  112. if prometheusEnabled {
  113. incrementPrometheusErrorsTotal("download")
  114. }
  115. panic(err)
  116. }
  117. checkTimeout(ctx)
  118. if conf.ETagEnabled {
  119. eTag := calcETag(ctx)
  120. rw.Header().Set("ETag", eTag)
  121. if eTag == r.Header.Get("If-None-Match") {
  122. respondWithNotModified(ctx, reqID, r, rw)
  123. return
  124. }
  125. }
  126. checkTimeout(ctx)
  127. imageData, processcancel, err := processImage(ctx)
  128. defer processcancel()
  129. if err != nil {
  130. if newRelicEnabled {
  131. sendErrorToNewRelic(ctx, err)
  132. }
  133. if prometheusEnabled {
  134. incrementPrometheusErrorsTotal("processing")
  135. }
  136. panic(err)
  137. }
  138. checkTimeout(ctx)
  139. respondWithImage(ctx, reqID, r, rw, imageData)
  140. }