handler.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. package stream
  2. import (
  3. "context"
  4. "io"
  5. "log/slog"
  6. "net/http"
  7. "sync"
  8. "github.com/imgproxy/imgproxy/v3/cookies"
  9. "github.com/imgproxy/imgproxy/v3/fetcher"
  10. "github.com/imgproxy/imgproxy/v3/httpheaders"
  11. "github.com/imgproxy/imgproxy/v3/ierrors"
  12. "github.com/imgproxy/imgproxy/v3/monitoring"
  13. "github.com/imgproxy/imgproxy/v3/monitoring/stats"
  14. "github.com/imgproxy/imgproxy/v3/options"
  15. "github.com/imgproxy/imgproxy/v3/options/keys"
  16. "github.com/imgproxy/imgproxy/v3/server"
  17. )
  18. const (
  19. streamBufferSize = 4096 // Size of the buffer used for streaming
  20. categoryStreaming = "streaming" // Streaming error category
  21. )
  22. var (
  23. // streamBufPool is a sync.Pool for reusing byte slices used for streaming
  24. streamBufPool = sync.Pool{
  25. New: func() any {
  26. buf := make([]byte, streamBufferSize)
  27. return &buf
  28. },
  29. }
  30. )
  31. // Handler handles image passthrough requests, allowing images to be streamed directly
  32. type Handler struct {
  33. config *Config // Configuration for the streamer
  34. fetcher *fetcher.Fetcher // Fetcher instance to handle image fetching
  35. }
  36. // request holds the parameters and state for a single streaming request
  37. type request struct {
  38. handler *Handler
  39. imageRequest *http.Request
  40. imageURL string
  41. reqID string
  42. opts *options.Options
  43. rw server.ResponseWriter
  44. }
  45. // New creates new handler object
  46. func New(config *Config, fetcher *fetcher.Fetcher) (*Handler, error) {
  47. if err := config.Validate(); err != nil {
  48. return nil, err
  49. }
  50. return &Handler{
  51. fetcher: fetcher,
  52. config: config,
  53. }, nil
  54. }
  55. // Stream handles the image passthrough request, streaming the image directly to the response writer
  56. func (s *Handler) Execute(
  57. ctx context.Context,
  58. userRequest *http.Request,
  59. imageURL string,
  60. reqID string,
  61. o *options.Options,
  62. rw server.ResponseWriter,
  63. ) error {
  64. stream := &request{
  65. handler: s,
  66. imageRequest: userRequest,
  67. imageURL: imageURL,
  68. reqID: reqID,
  69. opts: o,
  70. rw: rw,
  71. }
  72. return stream.execute(ctx)
  73. }
  74. // execute handles the actual streaming logic
  75. func (s *request) execute(ctx context.Context) error {
  76. stats.IncImagesInProgress()
  77. defer stats.DecImagesInProgress()
  78. defer monitoring.StartStreamingSegment(ctx)()
  79. // Passthrough request headers from the original request
  80. requestHeaders := s.getImageRequestHeaders()
  81. cookieJar, err := s.getCookieJar()
  82. if err != nil {
  83. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryStreaming))
  84. }
  85. // Build the request to fetch the image
  86. r, err := s.handler.fetcher.BuildRequest(ctx, s.imageURL, requestHeaders, cookieJar)
  87. if r != nil {
  88. defer r.Cancel()
  89. }
  90. if err != nil {
  91. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryStreaming))
  92. }
  93. // Send the request to fetch the image
  94. res, err := r.Send()
  95. if res != nil {
  96. defer res.Body.Close()
  97. }
  98. if err != nil {
  99. return ierrors.Wrap(err, 0, ierrors.WithCategory(categoryStreaming))
  100. }
  101. // Output streaming response headers
  102. s.rw.SetOriginHeaders(res.Header)
  103. s.rw.Passthrough(s.handler.config.PassthroughResponseHeaders...) // NOTE: priority? This is lowest as it was
  104. s.rw.SetContentLength(int(res.ContentLength))
  105. s.rw.SetCanonical(s.imageURL)
  106. s.rw.SetExpires(s.opts.GetTime(keys.Expires))
  107. // Set the Content-Disposition header
  108. s.setContentDisposition(r.URL().Path, res)
  109. // Copy the status code from the original response
  110. s.rw.WriteHeader(res.StatusCode)
  111. // Write the actual data
  112. s.streamData(res)
  113. return nil
  114. }
  115. // getCookieJar returns non-empty cookie jar if cookie passthrough is enabled
  116. func (s *request) getCookieJar() (http.CookieJar, error) {
  117. if !s.handler.config.CookiePassthrough {
  118. return nil, nil
  119. }
  120. return cookies.JarFromRequest(s.imageRequest)
  121. }
  122. // getImageRequestHeaders returns a new http.Header containing only
  123. // the headers that should be passed through from the user request
  124. func (s *request) getImageRequestHeaders() http.Header {
  125. h := make(http.Header)
  126. httpheaders.CopyFromRequest(s.imageRequest, h, s.handler.config.PassthroughRequestHeaders)
  127. return h
  128. }
  129. // setContentDisposition writes the headers to the response writer
  130. func (s *request) setContentDisposition(imagePath string, serverResponse *http.Response) {
  131. // Try to set correct Content-Disposition file name and extension
  132. if serverResponse.StatusCode < 200 || serverResponse.StatusCode >= 300 {
  133. return
  134. }
  135. ct := serverResponse.Header.Get(httpheaders.ContentType)
  136. s.rw.SetContentDisposition(
  137. imagePath,
  138. s.opts.GetString(keys.Filename, ""),
  139. "",
  140. ct,
  141. s.opts.GetBool(keys.ReturnAttachment, false),
  142. )
  143. }
  144. // streamData copies the image data from the response body to the response writer
  145. func (s *request) streamData(res *http.Response) {
  146. buf := streamBufPool.Get().(*[]byte)
  147. defer streamBufPool.Put(buf)
  148. _, copyerr := io.CopyBuffer(s.rw, res.Body, *buf)
  149. server.LogResponse(
  150. s.reqID, s.imageRequest, res.StatusCode, nil,
  151. slog.String("image_url", s.imageURL),
  152. slog.Any("processing_options", s.opts),
  153. )
  154. // We've got to skip logging here
  155. if copyerr != nil {
  156. panic(http.ErrAbortHandler)
  157. }
  158. }