processing_handler.go 4.6 KB

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