返回 DeepSeek-Reasonix
stall_test.go
根目录 / internal / provider / openai / stall_test.go
1 package openai
2
3 import (
4 "context"
5 "io"
6 "net/http"
7 "net/http/httptest"
8 "strings"
9 "testing"
10 "time"
11
12 "reasonix/internal/provider"
13 )
14
15 func TestDefaultStreamIdleTimeoutIsFiveMinutes(t *testing.T) {
16 if defaultStreamIdleTimeout != 300*time.Second {
17 t.Fatalf("default stream idle timeout = %s, want 5m", defaultStreamIdleTimeout)
18 }
19 }
20
21 // TestStreamStallTimesOut covers issue #3374: a half-open connection (a proxy
22 // switched mid-stream) sends the SSE head then goes silent without an RST, so
23 // scanner.Scan() would block forever and Ctrl+C-less sessions hang until kill -9.
24 // The idle watchdog must surface a stall error instead of hanging.
25 func TestStreamStallTimesOut(t *testing.T) {
26 release := make(chan struct{})
27 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
28 w.Header().Set("Content-Type", "text/event-stream")
29 w.WriteHeader(http.StatusOK)
30 flush(w)
31 _, _ = io.WriteString(w, ": keep-alive\n\n") // one comment, resets the watchdog once
32 flush(w)
33 <-release // then stall: never send data, never close — half-open connection
34 }))
35 defer srv.Close()
36 defer close(release)
37
38 p, err := New(provider.Config{Name: "deepseek", BaseURL: srv.URL, Model: "deepseek-v4", APIKey: "k"})
39 if err != nil {
40 t.Fatalf("New: %v", err)
41 }
42 p.(*client).idleTimeout = 150 * time.Millisecond
43 ch, err := p.Stream(context.Background(), provider.Request{Messages: []provider.Message{{Role: provider.RoleUser, Content: "hi"}}})
44 if err != nil {
45 t.Fatalf("Stream: %v", err)
46 }
47
48 deadline := time.After(5 * time.Second)
49 for {
50 select {
51 case chunk, ok := <-ch:
52 if !ok {
53 t.Fatal("stream closed without surfacing a stall error")
54 }
55 if chunk.Type == provider.ChunkError {
56 if !strings.Contains(chunk.Err.Error(), "stalled") {
57 t.Fatalf("error = %v, want a 'stalled' error", chunk.Err)
58 }
59 return
60 }
61 case <-deadline:
62 t.Fatal("stream did not time out on a stalled connection — it hung")
63 }
64 }
65 }
66
67 func TestReadStreamSendUnblocksOnContextCancel(t *testing.T) {
68 ctx, cancel := context.WithCancel(context.Background())
69 resp := &http.Response{Body: io.NopCloser(strings.NewReader("data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\n"))}
70 out := make(chan provider.Chunk)
71 done := make(chan struct{})
72
73 go func() {
74 _, _ = (&client{name: "openai"}).readStream(ctx, resp, out)
75 close(done)
76 }()
77
78 time.Sleep(50 * time.Millisecond)
79 cancel()
80
81 select {
82 case <-done:
83 case <-time.After(500 * time.Millisecond):
84 t.Fatal("readStream remained blocked sending to an abandoned reader after context cancellation")
85 }
86 }
87
88 func flush(w http.ResponseWriter) {
89 if f, ok := w.(http.Flusher); ok {
90 f.Flush()
91 }
92 }
93
93 lines GO