1
0

handler.go 5.1 KB

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