Skip to content

Commit ba76dfa

Browse files
striker2000willnorris
authored andcommitted
Limit number of running transformation threads
1 parent 731fa16 commit ba76dfa

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

imageproxy.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"net/http"
2121
"net/url"
2222
"path"
23+
"runtime"
2324
"strings"
2425
"time"
2526

@@ -125,6 +126,7 @@ func NewProxy(transport http.RoundTripper, cache Cache) *Proxy {
125126
Transport: &TransformingTransport{
126127
Transport: transport,
127128
CachingClient: client,
129+
limiter: make(chan struct{}, runtime.NumCPU()),
128130
log: func(format string, v ...any) {
129131
if proxy.Verbose {
130132
proxy.logf(format, v...)
@@ -557,6 +559,9 @@ type TransformingTransport struct {
557559
// responses are properly cached.
558560
CachingClient *http.Client
559561

562+
// limiter limits the number of concurrent transformations being processed.
563+
limiter chan struct{}
564+
560565
log func(format string, v ...any)
561566

562567
updateCacheHeaders func(hdr http.Header)
@@ -598,6 +603,15 @@ func (t *TransformingTransport) RoundTrip(req *http.Request) (*http.Response, er
598603
}, nil
599604
}
600605

606+
// enforce limiter after we've checked if we can early return a 304 response,
607+
// but before we read the response body and perform transformations.
608+
if t.limiter != nil {
609+
t.limiter <- struct{}{}
610+
defer func() {
611+
<-t.limiter
612+
}()
613+
}
614+
601615
b, err := io.ReadAll(resp.Body)
602616
if err != nil {
603617
return nil, err

imageproxy_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -735,6 +735,7 @@ func TestTransformingTransport(t *testing.T) {
735735
tr := &TransformingTransport{
736736
Transport: &testTransport{},
737737
CachingClient: client,
738+
limiter: make(chan struct{}, 1),
738739
}
739740
client.Transport = tr
740741

0 commit comments

Comments
 (0)