-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprocess.go
263 lines (229 loc) · 6.98 KB
/
process.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"time"
"github.com/gin-gonic/gin"
"golang.org/x/net/context"
)
func processRequest(c *gin.Context, upstream *OPENAI_UPSTREAM, record *Record, shouldResponse bool) error {
var errCtx []error
record.UpstreamEndpoint = upstream.Endpoint
record.UpstreamSK = upstream.SK
record.Response = ""
// [TODO] record request body
// reverse proxy
remote, err := url.Parse(upstream.Endpoint)
if err != nil {
return err
}
path := strings.TrimPrefix(c.Request.URL.Path, "/v1")
// recoognize whisper url
remote.Path = upstream.URL.Path + path
log.Println("[proxy.begin]:", remote)
log.Println("[proxy.begin]: shouldResposne:", shouldResponse)
haveResponse := false
proxy := httputil.NewSingleHostReverseProxy(remote)
proxy.Director = nil
var inBody []byte
proxy.Rewrite = func(proxyRequest *httputil.ProxyRequest) {
in := proxyRequest.In
ctx, cancel := context.WithCancel(context.Background())
proxyRequest.Out = proxyRequest.Out.WithContext(ctx)
out := proxyRequest.Out
// read request body
inBody, err = io.ReadAll(in.Body)
if err != nil {
errCtx = append(errCtx, ErrReadRequestBody)
return
}
// record chat message from user
requestBody, requestBodyOK := ParseRequestBody(inBody)
// record if parse success
if requestBodyOK == nil && requestBody.Model != "" {
record.Model = requestBody.Model
record.Body = string(inBody)
}
// check allow list
if len(upstream.Allow) > 0 {
isAllow := false
for _, allow := range upstream.Allow {
if allow == record.Model {
isAllow = true
break
}
}
if !isAllow {
errCtx = append(errCtx, errors.New("[proxy.rewrite]: model '"+record.Model+"' not allowed"))
return
}
}
// check block list
if len(upstream.Deny) > 0 {
for _, deny := range upstream.Deny {
if deny == record.Model {
errCtx = append(errCtx, errors.New("[proxy.rewrite]: model '"+record.Model+"' denied"))
return
}
}
}
// set timeout, default is 60 second
timeout := time.Duration(upstream.Timeout) * time.Second
if requestBodyOK == nil && requestBody.Stream {
timeout = time.Duration(upstream.StreamTimeout) * time.Second
}
// timeout out request
go func() {
time.Sleep(timeout)
if !haveResponse {
log.Println("[proxy.timeout]: Timeout upstream", upstream.Endpoint, timeout)
errTimeout := errors.New("[proxy.timeout]: Timeout upstream")
errCtx = append(errCtx, errTimeout)
if shouldResponse {
c.Header("Content-Type", "application/json")
sendCORSHeaders(c)
c.AbortWithError(502, errTimeout)
}
cancel()
}
}()
out.Body = io.NopCloser(bytes.NewReader(inBody))
out.Host = remote.Host
out.URL.Scheme = remote.Scheme
out.URL.Host = remote.Host
if !upstream.KeepHeader {
out.Header = http.Header{}
}
out.Header.Set("Host", remote.Host)
if upstream.SK == "asis" {
out.Header.Set("Authorization", c.Request.Header.Get("Authorization"))
} else {
out.Header.Set("Authorization", "Bearer "+upstream.SK)
}
out.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
}
var buf bytes.Buffer
var contentType string
proxy.ModifyResponse = func(r *http.Response) error {
haveResponse = true
record.ResponseTime = time.Since(record.CreatedAt)
record.Status = r.StatusCode
// remove response's cors headers
r.Header.Del("Access-Control-Allow-Origin")
r.Header.Del("Access-Control-Allow-Methods")
r.Header.Del("Access-Control-Allow-Headers")
r.Header.Del("access-control-allow-origin")
r.Header.Del("access-control-allow-methods")
r.Header.Del("access-control-allow-headers")
if !shouldResponse && r.StatusCode != 200 {
log.Println("[proxy.modifyResponse]: upstream return not 200 and should not response", r.StatusCode)
return errors.New("upstream return not 200 and should not response")
}
if r.StatusCode != 200 {
body, err := io.ReadAll(r.Body)
if err != nil {
errRet := errors.New("[proxy.modifyResponse]: failed to read response from upstream " + err.Error())
return errRet
}
errRet := fmt.Errorf("[error]: openai-api-route upstream return '%s' with '%s'", r.Status, string(body))
log.Println(errRet)
record.Status = r.StatusCode
return errRet
}
// handle reverse proxy cors header if upstream do not set that
sendCORSHeaders(c)
// count success
r.Body = io.NopCloser(io.TeeReader(r.Body, &buf))
contentType = r.Header.Get("content-type")
return nil
}
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
haveResponse = true
record.ResponseTime = time.Since(record.CreatedAt)
log.Println("[proxy.errorHandler]", err, upstream.SK, upstream.Endpoint, errCtx)
errCtx = append(errCtx, err)
// abort to error handle
if shouldResponse {
c.Header("Content-Type", "application/json")
sendCORSHeaders(c)
for _, err := range errCtx {
c.AbortWithError(502, err)
}
}
log.Println("[proxy.errorHandler]: response is", r.Response)
if record.Status == 0 {
record.Status = 502
}
record.Response += "[proxy.ErrorHandler]: " + err.Error()
if r.Response != nil {
record.Status = r.Response.StatusCode
}
}
err = ServeHTTP(proxy, c.Writer, c.Request)
if err != nil {
log.Println("[proxy.serve]: error from ServeHTTP:", err)
// panic means client has abort the http connection
// since the connection is lost, we return
// and the reverse process should not try the next upsteam
return http.ErrAbortHandler
}
// return context error
if len(errCtx) > 0 {
log.Println("[proxy.serve]: error from ServeHTTP:", errCtx)
// fix inrequest body
c.Request.Body = io.NopCloser(bytes.NewReader(inBody))
return errCtx[len(errCtx)-1]
}
resp, err := io.ReadAll(io.NopCloser(&buf))
if err != nil {
record.Response = "failed to read response from upstream " + err.Error()
log.Println(record.Response)
} else {
// record response
// stream mode
if strings.HasPrefix(contentType, "text/event-stream") {
for _, line := range strings.Split(string(resp), "\n") {
chunk := StreamModeChunk{}
line = strings.TrimPrefix(line, "data:")
line = strings.TrimSpace(line)
if line == "" {
continue
}
err := json.Unmarshal([]byte(line), &chunk)
if err != nil {
log.Println("[proxy.parseChunkError]:", err)
continue
}
if len(chunk.Choices) == 0 {
continue
}
record.Response += chunk.Choices[0].Delta.Content
}
} else if strings.HasPrefix(contentType, "text") {
record.Response = string(resp)
} else if strings.HasPrefix(contentType, "application/json") {
// fallback record response
if len(resp) < 1024*128 {
record.Response = string(resp)
}
var fetchResp FetchModeResponse
err := json.Unmarshal(resp, &fetchResp)
if err == nil {
if len(fetchResp.Choices) > 0 {
record.Response = fetchResp.Choices[0].Message.Content
}
}
} else {
log.Println("[proxy.record]: Unknown content type", contentType)
}
}
return nil
}