Skip to content

Commit 7ed69cb

Browse files
authored
Merge pull request #11 from dappnode/fix/no-response-duration-limit
fix: no limit on response duration, only stall guards
2 parents 27bdd2e + 8d08a97 commit 7ed69cb

16 files changed

Lines changed: 565 additions & 17 deletions

‎README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,13 @@ keep a valid `Retry-After` header. Errors include `origin` (`gateway` or
8888
details are not exposed. A configured fallback provider is tried only after a
8989
rate limit or a server-side failure, never after a rejected request.
9090

91+
Responses have no limit on total duration. Two stall guards apply instead:
92+
`PROVIDER_SILENCE_TIMEOUT_SECONDS` (default 900) ends a request when the
93+
provider sends nothing, neither headers nor bytes, for that long, and
94+
`CLIENT_IO_TIMEOUT_SECONDS` (default 60) ends one when a single read from or
95+
write to the client is blocked for that long. Both must be positive whole
96+
seconds.
97+
9198
## Privacy and usage controls
9299

93100
Nexus provides per-key PII masking settings and access to privacy-focused

‎apps/gateway/internal/adapters/http/handlers/confidential_chat_completions_handler_test.go‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"testing"
1212
"time"
1313

14+
"github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/adapters/http/middleware"
1415
"github.com/google/uuid"
1516
"github.com/tinfoilsh/encrypted-http-body-protocol/identity"
1617
"github.com/tinfoilsh/encrypted-http-body-protocol/protocol"
@@ -108,6 +109,49 @@ func TestConfidentialChatCompletionsHandler_StreamsEncryptedResponse(t *testing.
108109
}
109110
}
110111

112+
func TestConfidentialStreamRefreshesNetworkWriteDeadline(t *testing.T) {
113+
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
114+
w.Header().Set("Content-Type", "text/event-stream")
115+
for i := 0; i < 6; i++ {
116+
_, _ = io.WriteString(w, "data: token\n\n")
117+
w.(http.Flusher).Flush()
118+
time.Sleep(30 * time.Millisecond)
119+
}
120+
_, _ = io.WriteString(w, "data: [DONE]\n\n")
121+
w.(http.Flusher).Flush()
122+
})
123+
handler, clientIdentity := newConfidentialTestHandler(t, next)
124+
server := httptest.NewUnstartedServer(middleware.WriteTimeout(time.Second)(http.HandlerFunc(handler.Handle)))
125+
server.Config.WriteTimeout = 50 * time.Millisecond
126+
server.Start()
127+
defer server.Close()
128+
request, requestContext, _ := newEncryptedConfidentialRequest(t, clientIdentity, envelopeAt(
129+
time.Now(), uuid.NewString(), json.RawMessage(`{"model":"test","stream":true,"messages":[]}`),
130+
))
131+
request.URL.Scheme, request.URL.Host = "http", server.Listener.Addr().String()
132+
request.RequestURI = ""
133+
response, err := server.Client().Do(request)
134+
if err != nil {
135+
t.Fatal(err)
136+
}
137+
defer response.Body.Close()
138+
ciphertext, err := io.ReadAll(response.Body)
139+
if err != nil {
140+
t.Fatalf("encrypted stream ended early: %v", err)
141+
}
142+
if bytes.Contains(ciphertext, []byte("data: token")) {
143+
t.Fatal("encrypted stream exposed plaintext")
144+
}
145+
recorder := httptest.NewRecorder()
146+
recorder.HeaderMap = response.Header.Clone()
147+
recorder.Code = response.StatusCode
148+
_, _ = recorder.Body.Write(ciphertext)
149+
plaintext := decryptConfidentialResponse(t, recorder, requestContext)
150+
if got, want := string(plaintext), strings.Repeat("data: token\n\n", 6)+"data: [DONE]\n\n"; got != want {
151+
t.Fatalf("stream = %q, want %q", got, want)
152+
}
153+
}
154+
111155
func TestConfidentialChatCompletionsHandler_EncryptsAuthenticationErrors(t *testing.T) {
112156
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
113157
if _, err := ExtractBearerToken(r); err != nil {
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package middleware
2+
3+
import (
4+
"io"
5+
"net/http"
6+
"time"
7+
)
8+
9+
// ReadTimeout bounds each upload read, not the total upload or inference time.
10+
// Header reading remains bounded separately by http.Server.ReadHeaderTimeout.
11+
func ReadTimeout(timeout time.Duration) func(http.Handler) http.Handler {
12+
return func(next http.Handler) http.Handler {
13+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
14+
controller := http.NewResponseController(w)
15+
_ = controller.SetReadDeadline(time.Time{})
16+
if r.Body != nil {
17+
r.Body = &readTimeoutBody{ReadCloser: r.Body, controller: controller, timeout: timeout}
18+
}
19+
next.ServeHTTP(w, r)
20+
})
21+
}
22+
}
23+
24+
type readTimeoutBody struct {
25+
io.ReadCloser
26+
controller *http.ResponseController
27+
timeout time.Duration
28+
}
29+
30+
func (b *readTimeoutBody) Read(buffer []byte) (int, error) {
31+
_ = b.controller.SetReadDeadline(time.Now().Add(b.timeout))
32+
n, err := b.ReadCloser.Read(buffer[:min(len(buffer), maxTransferChunk)])
33+
if err != nil {
34+
_ = b.controller.SetReadDeadline(time.Time{})
35+
}
36+
return n, err
37+
}
38+
39+
func (b *readTimeoutBody) Close() error {
40+
_ = b.controller.SetReadDeadline(time.Now().Add(b.timeout))
41+
err := b.ReadCloser.Close()
42+
_ = b.controller.SetReadDeadline(time.Time{})
43+
return err
44+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package middleware
2+
3+
import (
4+
"fmt"
5+
"io"
6+
"net/http"
7+
"net/http/httptest"
8+
"testing"
9+
"time"
10+
)
11+
12+
func TestActiveUploadAndModelWaitOutliveAbsoluteDeadlines(t *testing.T) {
13+
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
14+
body, err := io.ReadAll(r.Body)
15+
if err != nil {
16+
w.WriteHeader(400)
17+
return
18+
}
19+
// Waiting for model work must not inherit the final upload deadline.
20+
time.Sleep(200 * time.Millisecond)
21+
fmt.Fprint(w, string(body))
22+
})
23+
server := httptest.NewUnstartedServer(ReadTimeout(150 * time.Millisecond)(WriteTimeout(150 * time.Millisecond)(handler)))
24+
server.Config.ReadTimeout = 50 * time.Millisecond
25+
server.Config.WriteTimeout = 50 * time.Millisecond
26+
server.Start()
27+
defer server.Close()
28+
reader, writer := io.Pipe()
29+
go func() {
30+
defer writer.Close()
31+
for i := 0; i < 8; i++ {
32+
if _, err := writer.Write([]byte("x")); err != nil {
33+
return
34+
}
35+
time.Sleep(25 * time.Millisecond)
36+
}
37+
}()
38+
response, err := server.Client().Post(server.URL, "text/plain", reader)
39+
if err != nil {
40+
t.Fatal(err)
41+
}
42+
defer response.Body.Close()
43+
body, err := io.ReadAll(response.Body)
44+
if err != nil || response.StatusCode != 200 || string(body) != "xxxxxxxx" {
45+
t.Fatalf("active upload/model wait interrupted: %d %q %v", response.StatusCode, body, err)
46+
}
47+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package middleware
2+
3+
import (
4+
"io"
5+
"net/http"
6+
"time"
7+
)
8+
9+
const maxTransferChunk = 32 << 10
10+
11+
// WriteTimeout bounds each network write, including encrypted response frames.
12+
// It replaces an absolute server WriteTimeout, which would cut off a healthy
13+
// long-running stream even while tokens and keepalives continue arriving.
14+
func WriteTimeout(timeout time.Duration) func(http.Handler) http.Handler {
15+
return func(next http.Handler) http.Handler {
16+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
17+
controller := http.NewResponseController(w)
18+
_ = controller.SetWriteDeadline(time.Time{})
19+
next.ServeHTTP(&writeTimeoutWriter{ResponseWriter: w, controller: controller, timeout: timeout}, r)
20+
})
21+
}
22+
}
23+
24+
type writeTimeoutWriter struct {
25+
http.ResponseWriter
26+
controller *http.ResponseController
27+
timeout time.Duration
28+
}
29+
30+
func (w *writeTimeoutWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }
31+
32+
func (w *writeTimeoutWriter) Write(body []byte) (int, error) {
33+
if len(body) == 0 {
34+
_ = w.controller.SetWriteDeadline(time.Now().Add(w.timeout))
35+
return w.ResponseWriter.Write(body)
36+
}
37+
var written int
38+
for len(body) > 0 {
39+
chunk := body[:min(len(body), maxTransferChunk)]
40+
_ = w.controller.SetWriteDeadline(time.Now().Add(w.timeout))
41+
n, err := w.ResponseWriter.Write(chunk)
42+
written += n
43+
if err != nil {
44+
return written, err
45+
}
46+
if n != len(chunk) {
47+
return written, io.ErrShortWrite
48+
}
49+
body = body[n:]
50+
}
51+
return written, nil
52+
}
53+
54+
func (w *writeTimeoutWriter) WriteHeader(status int) {
55+
_ = w.controller.SetWriteDeadline(time.Now().Add(w.timeout))
56+
w.ResponseWriter.WriteHeader(status)
57+
}
58+
59+
func (w *writeTimeoutWriter) FlushError() error {
60+
_ = w.controller.SetWriteDeadline(time.Now().Add(w.timeout))
61+
return w.controller.Flush()
62+
}
63+
64+
func (w *writeTimeoutWriter) Flush() { _ = w.FlushError() }
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package middleware
2+
3+
import (
4+
"fmt"
5+
"io"
6+
"net/http"
7+
"net/http/httptest"
8+
"strings"
9+
"testing"
10+
"time"
11+
)
12+
13+
func TestActiveStreamOutlivesAbsoluteServerDeadline(t *testing.T) {
14+
handler := WriteTimeout(100 * time.Millisecond)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
15+
for i := 0; i < 6; i++ {
16+
if _, err := fmt.Fprint(w, "data: token\n\n"); err != nil {
17+
return
18+
}
19+
w.(http.Flusher).Flush()
20+
time.Sleep(30 * time.Millisecond)
21+
}
22+
fmt.Fprint(w, "data: [DONE]\n\n")
23+
}))
24+
srv := httptest.NewUnstartedServer(handler)
25+
srv.Config.WriteTimeout = 50 * time.Millisecond
26+
srv.Start()
27+
defer srv.Close()
28+
resp, err := srv.Client().Get(srv.URL)
29+
if err != nil {
30+
t.Fatal(err)
31+
}
32+
defer resp.Body.Close()
33+
body, err := io.ReadAll(resp.Body)
34+
if err != nil || !strings.Contains(string(body), "[DONE]") {
35+
t.Fatalf("active stream interrupted: %v %q", err, body)
36+
}
37+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package openai
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"net/http"
7+
"net/http/httptest"
8+
"testing"
9+
"time"
10+
)
11+
12+
func TestNonStreamingKeepalivesOutliveSilenceTimeout(t *testing.T) {
13+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
14+
w.Header().Set("Content-Type", "application/json")
15+
for i := 0; i < 8; i++ {
16+
fmt.Fprint(w, "\n")
17+
w.(http.Flusher).Flush()
18+
time.Sleep(25 * time.Millisecond)
19+
}
20+
fmt.Fprint(w, `{"choices":[{"message":{"content":"complete"}}]}`)
21+
}))
22+
defer server.Close()
23+
body, err := NewClient(150*time.Millisecond).Do(context.Background(), server.URL, "fixture", map[string]any{"model": "test"})
24+
if err != nil || len(body) == 0 {
25+
t.Fatalf("active JSON response ended early: %v", err)
26+
}
27+
}

‎apps/gateway/internal/adapters/providers/openai/client.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"strings"
1515
"time"
1616

17+
providerstream "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/adapters/providers/stream"
1718
enclavenetwork "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/enclave/network"
1819
)
1920

@@ -51,9 +52,6 @@ func (c *Client) Do(ctx context.Context, baseURL, apiKey string, body map[string
5152

5253
// DoEndpoint uses the same bounded, enclave-aware transport for JSON APIs.
5354
func (c *Client) DoEndpoint(ctx context.Context, baseURL, endpoint, apiKey string, body map[string]any) ([]byte, error) {
54-
ctx, cancel := context.WithTimeout(ctx, c.responseTimeout)
55-
defer cancel()
56-
5755
jsonBody, err := json.Marshal(body)
5856
if err != nil {
5957
return nil, fmt.Errorf("failed to marshal request: %w", err)
@@ -70,6 +68,7 @@ func (c *Client) DoEndpoint(ctx context.Context, baseURL, endpoint, apiKey strin
7068
if err != nil {
7169
return nil, fmt.Errorf("provider request failed: %w", err)
7270
}
71+
resp.Body = providerstream.WithIdleTimeout(resp.Body, c.responseTimeout)
7372
defer resp.Body.Close()
7473

7574
respBody, err := io.ReadAll(io.LimitReader(resp.Body, 10*1024*1024))
@@ -108,6 +107,7 @@ func (c *Client) DoStream(ctx context.Context, baseURL, apiKey string, body map[
108107
return nil, ParseProviderResponseError(resp, body)
109108
}
110109

110+
resp.Body = providerstream.WithIdleTimeout(resp.Body, c.responseTimeout)
111111
return resp, nil
112112
}
113113

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package stream
2+
3+
import (
4+
"context"
5+
"io"
6+
"net/http"
7+
"sync"
8+
"time"
9+
)
10+
11+
// DoWithHeaderTimeout bounds the wait for headers without imposing a deadline
12+
// on the response body or changing the caller's verified HTTP transport.
13+
func DoWithHeaderTimeout(client *http.Client, request *http.Request, timeout time.Duration) (*http.Response, error) {
14+
if timeout <= 0 {
15+
return client.Do(request)
16+
}
17+
parent := request.Context()
18+
ctx, cancel := context.WithCancel(parent)
19+
var mu sync.Mutex
20+
waiting, expired := true, false
21+
timer := time.AfterFunc(timeout, func() {
22+
mu.Lock()
23+
defer mu.Unlock()
24+
if waiting {
25+
expired = true
26+
cancel()
27+
}
28+
})
29+
response, err := client.Do(request.WithContext(ctx))
30+
mu.Lock()
31+
waiting = false
32+
timer.Stop()
33+
timedOut := expired
34+
mu.Unlock()
35+
if timedOut && parent.Err() == nil {
36+
cancel()
37+
if response != nil {
38+
_ = response.Body.Close()
39+
}
40+
return nil, context.DeadlineExceeded
41+
}
42+
if err != nil {
43+
cancel()
44+
return response, err
45+
}
46+
response.Body = &cancelBody{ReadCloser: response.Body, cancel: cancel}
47+
return response, nil
48+
}
49+
50+
type cancelBody struct {
51+
io.ReadCloser
52+
cancel context.CancelFunc
53+
}
54+
55+
func (b *cancelBody) Close() error { b.cancel(); return b.ReadCloser.Close() }

0 commit comments

Comments
 (0)