processing_handler.go 5.2 KB

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