-
Notifications
You must be signed in to change notification settings - Fork 298
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: immediately flush data to client for event-stream response (#3375)
- Loading branch information
Showing
3 changed files
with
212 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
package proxy | ||
|
||
import ( | ||
"io" | ||
"sync" | ||
"time" | ||
) | ||
|
||
// copy from golang library, see https://github.com/golang/go/blob/master/src/net/http/httputil/reverseproxy.go | ||
type maxLatencyWriter struct { | ||
dst io.Writer | ||
flush func() error | ||
latency time.Duration // non-zero; negative means to flush immediately | ||
|
||
mu sync.Mutex // protects t, flushPending, and dst.Flush | ||
t *time.Timer | ||
flushPending bool | ||
} | ||
|
||
func (m *maxLatencyWriter) Write(p []byte) (n int, err error) { | ||
m.mu.Lock() | ||
defer m.mu.Unlock() | ||
n, err = m.dst.Write(p) | ||
if m.latency < 0 { | ||
m.flush() // nolint: errcheck | ||
return | ||
} | ||
if m.flushPending { | ||
return | ||
} | ||
if m.t == nil { | ||
m.t = time.AfterFunc(m.latency, m.delayedFlush) | ||
} else { | ||
m.t.Reset(m.latency) | ||
} | ||
m.flushPending = true | ||
return | ||
} | ||
|
||
func (m *maxLatencyWriter) delayedFlush() { | ||
m.mu.Lock() | ||
defer m.mu.Unlock() | ||
if !m.flushPending { // if stop was called but AfterFunc already started this goroutine | ||
return | ||
} | ||
m.flush() // nolint: errcheck | ||
m.flushPending = false | ||
} | ||
|
||
func (m *maxLatencyWriter) stop() { | ||
m.mu.Lock() | ||
defer m.mu.Unlock() | ||
m.flushPending = false | ||
if m.t != nil { | ||
m.t.Stop() | ||
} | ||
} |