processing_handler.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. fallbackImage *imageData
  16. )
  17. func initProcessingHandler() error {
  18. var err error
  19. processingSem = make(chan struct{}, conf.Concurrency)
  20. if conf.GZipCompression > 0 {
  21. responseGzipBufPool = newBufPool("gzip", conf.Concurrency, conf.GZipBufferSize)
  22. if responseGzipPool, err = newGzipPool(conf.Concurrency); err != nil {
  23. return err
  24. }
  25. }
  26. vary := make([]string, 0)
  27. if conf.EnableWebpDetection || conf.EnforceWebp {
  28. vary = append(vary, "Accept")
  29. }
  30. if conf.GZipCompression > 0 {
  31. vary = append(vary, "Accept-Encoding")
  32. }
  33. if conf.EnableClientHints {
  34. vary = append(vary, "DPR", "Viewport-Width", "Width")
  35. }
  36. headerVaryValue = strings.Join(vary, ", ")
  37. if fallbackImage, err = getFallbackImageData(); err != nil {
  38. return err
  39. }
  40. return nil
  41. }
  42. func respondWithImage(ctx context.Context, reqID string, r *http.Request, rw http.ResponseWriter, data []byte) {
  43. po := getProcessingOptions(ctx)
  44. var contentDisposition string
  45. if len(po.Filename) > 0 {
  46. contentDisposition = po.Format.ContentDisposition(po.Filename)
  47. } else {
  48. contentDisposition = po.Format.ContentDispositionFromURL(getImageURL(ctx))
  49. }
  50. rw.Header().Set("Content-Type", po.Format.Mime())
  51. rw.Header().Set("Content-Disposition", contentDisposition)
  52. if conf.SetCanonicalHeader {
  53. origin := getImageURL(ctx)
  54. if strings.HasPrefix(origin, "https://") || strings.HasPrefix(origin, "http://") {
  55. linkHeader := fmt.Sprintf(`<%s>; rel="canonical"`, origin)
  56. rw.Header().Set("Link", linkHeader)
  57. }
  58. }
  59. var cacheControl, expires string
  60. if conf.CacheControlPassthrough {
  61. cacheControl = getCacheControlHeader(ctx)
  62. expires = getExpiresHeader(ctx)
  63. }
  64. if len(cacheControl) == 0 && len(expires) == 0 {
  65. cacheControl = fmt.Sprintf("max-age=%d, public", conf.TTL)
  66. expires = time.Now().Add(time.Second * time.Duration(conf.TTL)).Format(http.TimeFormat)
  67. }
  68. if len(cacheControl) > 0 {
  69. rw.Header().Set("Cache-Control", cacheControl)
  70. }
  71. if len(expires) > 0 {
  72. rw.Header().Set("Expires", expires)
  73. }
  74. if len(headerVaryValue) > 0 {
  75. rw.Header().Set("Vary", headerVaryValue)
  76. }
  77. if conf.EnableDebugHeaders {
  78. imgdata := getImageData(ctx)
  79. rw.Header().Set("X-Origin-Content-Length", strconv.Itoa(len(imgdata.Data)))
  80. }
  81. if conf.GZipCompression > 0 && strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
  82. buf := responseGzipBufPool.Get(0)
  83. defer responseGzipBufPool.Put(buf)
  84. gz := responseGzipPool.Get(buf)
  85. defer responseGzipPool.Put(gz)
  86. gz.Write(data)
  87. gz.Close()
  88. rw.Header().Set("Content-Encoding", "gzip")
  89. rw.Header().Set("Content-Length", strconv.Itoa(buf.Len()))
  90. rw.WriteHeader(200)
  91. rw.Write(buf.Bytes())
  92. } else {
  93. rw.Header().Set("Content-Length", strconv.Itoa(len(data)))
  94. rw.WriteHeader(200)
  95. rw.Write(data)
  96. }
  97. imageURL := getImageURL(ctx)
  98. logResponse(reqID, r, 200, nil, &imageURL, po)
  99. // logResponse(reqID, r, 200, getTimerSince(ctx), getImageURL(ctx), po))
  100. }
  101. func respondWithNotModified(ctx context.Context, reqID string, r *http.Request, rw http.ResponseWriter) {
  102. rw.WriteHeader(304)
  103. imageURL := getImageURL(ctx)
  104. logResponse(reqID, r, 304, nil, &imageURL, getProcessingOptions(ctx))
  105. }
  106. func handleProcessing(reqID string, rw http.ResponseWriter, r *http.Request) {
  107. ctx := r.Context()
  108. if newRelicEnabled {
  109. var newRelicCancel context.CancelFunc
  110. ctx, newRelicCancel, rw = startNewRelicTransaction(ctx, rw, r)
  111. defer newRelicCancel()
  112. }
  113. if prometheusEnabled {
  114. prometheusRequestsTotal.Inc()
  115. defer startPrometheusDuration(prometheusRequestDuration)()
  116. }
  117. select {
  118. case processingSem <- struct{}{}:
  119. case <-ctx.Done():
  120. panic(newError(499, "Request was cancelled before processing", "Cancelled"))
  121. }
  122. defer func() { <-processingSem }()
  123. ctx, timeoutCancel := context.WithTimeout(ctx, time.Duration(conf.WriteTimeout)*time.Second)
  124. defer timeoutCancel()
  125. ctx, err := parsePath(ctx, r)
  126. if err != nil {
  127. panic(err)
  128. }
  129. ctx, downloadcancel, err := downloadImage(ctx)
  130. defer downloadcancel()
  131. if err != nil {
  132. if newRelicEnabled {
  133. sendErrorToNewRelic(ctx, err)
  134. }
  135. if prometheusEnabled {
  136. incrementPrometheusErrorsTotal("download")
  137. }
  138. if fallbackImage == nil {
  139. panic(err)
  140. }
  141. if ierr, ok := err.(*imgproxyError); !ok || ierr.Unexpected {
  142. reportError(err, r)
  143. }
  144. logWarning("Could not load image %s. Using fallback image. %s", getImageURL(ctx), err.Error())
  145. ctx = context.WithValue(ctx, imageDataCtxKey, fallbackImage)
  146. }
  147. checkTimeout(ctx)
  148. if conf.ETagEnabled {
  149. eTag := calcETag(ctx)
  150. rw.Header().Set("ETag", eTag)
  151. if eTag == r.Header.Get("If-None-Match") {
  152. respondWithNotModified(ctx, reqID, r, rw)
  153. return
  154. }
  155. }
  156. checkTimeout(ctx)
  157. if len(conf.SkipProcessingFormats) > 0 {
  158. imgdata := getImageData(ctx)
  159. po := getProcessingOptions(ctx)
  160. if imgdata.Type == po.Format || po.Format == imageTypeUnknown {
  161. for _, f := range conf.SkipProcessingFormats {
  162. if f == imgdata.Type {
  163. po.Format = imgdata.Type
  164. respondWithImage(ctx, reqID, r, rw, imgdata.Data)
  165. return
  166. }
  167. }
  168. }
  169. }
  170. imageData, processcancel, err := processImage(ctx)
  171. defer processcancel()
  172. if err != nil {
  173. if newRelicEnabled {
  174. sendErrorToNewRelic(ctx, err)
  175. }
  176. if prometheusEnabled {
  177. incrementPrometheusErrorsTotal("processing")
  178. }
  179. panic(err)
  180. }
  181. checkTimeout(ctx)
  182. respondWithImage(ctx, reqID, r, rw, imageData)
  183. }