|
| 1 | +package plugins |
| 2 | + |
| 3 | +import ( |
| 4 | + "net" |
| 5 | + "net/http" |
| 6 | + "net/http/httputil" |
| 7 | + "net/url" |
| 8 | + "sync" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/mirkobrombin/goup/internal/logger" |
| 12 | +) |
| 13 | + |
| 14 | +// upstreamTransport is shared by all plugin reverse proxies so connections to |
| 15 | +// application backends (Node, Python, Docker) are pooled and reused instead of |
| 16 | +// being re-dialed per request. |
| 17 | +var upstreamTransport = &http.Transport{ |
| 18 | + Proxy: http.ProxyFromEnvironment, |
| 19 | + DialContext: (&net.Dialer{ |
| 20 | + Timeout: 30 * time.Second, |
| 21 | + KeepAlive: 30 * time.Second, |
| 22 | + }).DialContext, |
| 23 | + ForceAttemptHTTP2: true, |
| 24 | + MaxIdleConns: 512, |
| 25 | + MaxIdleConnsPerHost: 128, |
| 26 | + IdleConnTimeout: 90 * time.Second, |
| 27 | + TLSHandshakeTimeout: 10 * time.Second, |
| 28 | + ExpectContinueTimeout: 1 * time.Second, |
| 29 | +} |
| 30 | + |
| 31 | +var upstreamProxies sync.Map // target URL -> *httputil.ReverseProxy |
| 32 | + |
| 33 | +// upstreamBufferPool recycles the copy buffers used by the reverse proxies so |
| 34 | +// small responses do not pay a fresh 32KB allocation per request. |
| 35 | +type upstreamBufferPool struct{ pool sync.Pool } |
| 36 | + |
| 37 | +func (p *upstreamBufferPool) Get() []byte { return p.pool.Get().([]byte) } |
| 38 | +func (p *upstreamBufferPool) Put(b []byte) { p.pool.Put(b) } |
| 39 | + |
| 40 | +var sharedBufferPool = &upstreamBufferPool{ |
| 41 | + pool: sync.Pool{ |
| 42 | + New: func() any { return make([]byte, 32*1024) }, |
| 43 | + }, |
| 44 | +} |
| 45 | + |
| 46 | +// upstreamProxy returns a shared streaming reverse proxy for the given |
| 47 | +// backend base URL (e.g. "http://localhost:3000"). Request and response |
| 48 | +// bodies are streamed end-to-end, never buffered in memory. |
| 49 | +func upstreamProxy(target string, l *logger.Logger) (*httputil.ReverseProxy, error) { |
| 50 | + if cached, ok := upstreamProxies.Load(target); ok { |
| 51 | + return cached.(*httputil.ReverseProxy), nil |
| 52 | + } |
| 53 | + |
| 54 | + parsed, err := url.Parse(target) |
| 55 | + if err != nil { |
| 56 | + return nil, err |
| 57 | + } |
| 58 | + |
| 59 | + rp := httputil.NewSingleHostReverseProxy(parsed) |
| 60 | + rp.Transport = upstreamTransport |
| 61 | + rp.BufferPool = sharedBufferPool |
| 62 | + rp.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) { |
| 63 | + if l != nil { |
| 64 | + l.Errorf("Proxy error for %s -> %s: %v", r.URL.Path, target, err) |
| 65 | + } |
| 66 | + http.Error(w, "Backend unavailable", http.StatusBadGateway) |
| 67 | + } |
| 68 | + |
| 69 | + actual, _ := upstreamProxies.LoadOrStore(target, rp) |
| 70 | + return actual.(*httputil.ReverseProxy), nil |
| 71 | +} |
0 commit comments