processing_handler.go 4.2 KB

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