Skip to content

Commit

Permalink
Flush stream response to make it stream (#1364)
Browse files Browse the repository at this point in the history
* update flush policy

* update response real time flush

* add comments
  • Loading branch information
suchen-sci authored Dec 31, 2024
1 parent efde105 commit 6b4ffd7
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions pkg/object/httpserver/mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ func (mi *muxInstance) sendResponse(ctx *context.Context, stdw http.ResponseWrit
stdw.WriteHeader(resp.StatusCode())

var writer io.Writer
if responseNeedFlush(resp) {
if responseIsRealTime(resp) {
writer = NewResponseFlushWriter(stdw)
} else {
writer = stdw
Expand Down Expand Up @@ -287,15 +287,25 @@ func NewResponseFlushWriter(w http.ResponseWriter) *ResponseFlushWriter {
}
}

func responseNeedFlush(resp *httpprot.Response) bool {
// responseIsRealTime returns whether the response needs to be flushed immediately.
// The response needs to be flushed immediately if the response has no content length (chunked),
// or the response is a Server-Sent Events response.
func responseIsRealTime(resp *httpprot.Response) bool {
// Based on https://en.wikipedia.org/wiki/Chunked_transfer_encoding
// If the Transfer-Encoding header field is present in a response and its value is "chunked",
// then the body of response is considered as a stream of chunks.
if len(resp.TransferEncoding) > 0 && resp.TransferEncoding[0] == "chunked" && resp.ContentLength <= 0 {
return true
}

resCTHeader := resp.Std().Header.Get("Content-Type")
resCT, _, err := mime.ParseMediaType(resCTHeader)

// For Server-Sent Events responses, flush immediately.
// The MIME type is defined in https://www.w3.org/TR/eventsource/#text-event-stream
if err == nil && resCT == "text/event-stream" {
return true
}

return false
}

Expand Down

0 comments on commit 6b4ffd7

Please sign in to comment.