-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathhandler.go
More file actions
267 lines (233 loc) · 8.1 KB
/
Copy pathhandler.go
File metadata and controls
267 lines (233 loc) · 8.1 KB
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
264
265
266
267
package proxy
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"strings"
"time"
"github.com/whtsky/copilot2api/auth"
"github.com/whtsky/copilot2api/internal/cache"
"github.com/whtsky/copilot2api/internal/upstream"
)
type Handler struct {
upstream *upstream.Client
authClient *auth.Client
modelsCache *cache.Cache[[]byte]
}
// NewHandler creates a new proxy handler.
// The transport is used for upstream HTTP requests (pass nil to create a new one).
func NewHandler(authClient *auth.Client, transport *http.Transport) *Handler {
return &Handler{
upstream: upstream.NewClient(authClient, transport),
authClient: authClient,
modelsCache: cache.New[[]byte](5 * time.Minute),
}
}
// WarmModels pre-populates the models cache to avoid cold-cache latency.
func (h *Handler) WarmModels(ctx context.Context) {
_, err := h.modelsCache.Get(ctx, func(ctx context.Context) ([]byte, error) {
return h.doModelsRequest(ctx)
})
if err != nil {
slog.Warn("failed to warm models cache", "error", err)
}
}
// doModelsRequest fetches /models from upstream.
func (h *Handler) doModelsRequest(ctx context.Context) ([]byte, error) {
_, respData, err := h.upstream.Do(ctx, upstream.Request{
Method: "GET",
Endpoint: "/models",
})
return respData, err
}
// ServeHTTP handles all proxy requests
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Extract endpoint from path
endpoint := strings.TrimPrefix(r.URL.Path, "/v1")
slog.Debug("proxy request", "method", r.Method, "path", r.URL.Path, "endpoint", endpoint)
switch endpoint {
case "/models":
h.handleModels(w, r)
case "/embeddings":
h.handleEmbeddings(w, r)
case "/chat/completions":
h.handlePassthrough(w, r, endpoint)
case "/responses":
h.handlePassthrough(w, r, endpoint)
default:
WriteOpenAIError(w, http.StatusNotFound, OpenAIErrorTypeInvalidRequest, "Endpoint not found")
}
}
// handleModels handles /v1/models with caching
func (h *Handler) handleModels(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
WriteOpenAIError(w, http.StatusMethodNotAllowed, OpenAIErrorTypeInvalidRequest, "Method not allowed")
return
}
respData, err := h.modelsCache.Get(r.Context(), func(ctx context.Context) ([]byte, error) {
return h.doModelsRequest(ctx)
})
if err != nil {
var upstreamErr *upstream.UpstreamError
if errors.As(err, &upstreamErr) {
upstreamErr.WriteRawError(w)
return
}
slog.Error("failed to fetch models", "error", err)
WriteOpenAIError(w, http.StatusInternalServerError, OpenAIErrorTypeServerError, "Internal server error")
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(respData)
}
// handlePassthrough handles direct passthrough requests
func (h *Handler) handlePassthrough(w http.ResponseWriter, r *http.Request, endpoint string) {
// Check body size before processing — reject oversized payloads with 413
var bodyBytes []byte
if r.Body != nil {
const maxBodySize = 10 << 20 // 10MB
var err error
bodyBytes, err = io.ReadAll(io.LimitReader(r.Body, maxBodySize+1))
if err != nil {
WriteOpenAIError(w, http.StatusBadRequest, OpenAIErrorTypeInvalidRequest, "Failed to read request body")
return
}
if len(bodyBytes) > maxBodySize {
WriteOpenAIError(w, http.StatusRequestEntityTooLarge, OpenAIErrorTypeInvalidRequest, "Request body too large")
return
}
r.Body = io.NopCloser(bytes.NewReader(bodyBytes))
}
h.handlePassthroughBody(w, r, endpoint, bodyBytes)
}
// handlePassthroughBody processes the passthrough request after the body has been read and validated.
// It takes pre-read body bytes to avoid redundant body reading.
func (h *Handler) handlePassthroughBody(w http.ResponseWriter, r *http.Request, endpoint string, bodyBytes []byte) {
// Check if this is a streaming request
if isStreamingRequest(bodyBytes) {
if err := h.HandleStreamingRequest(w, r, endpoint); err != nil {
slog.Error("streaming request failed", "endpoint", endpoint, "error", err)
// If headers were already sent we can't write an HTTP error.
// Otherwise, send a proper 502 so the client doesn't get an empty 200.
var hse *headersSentError
if !errors.As(err, &hse) {
WriteOpenAIError(w, http.StatusBadGateway, OpenAIErrorTypeServerError, "upstream request failed")
}
}
return
}
// Handle non-streaming request
respData, err := h.doNonStreamingRequest(r, endpoint)
if err != nil {
var upstreamErr *upstream.UpstreamError
if errors.As(err, &upstreamErr) {
// Forward upstream status code and body
upstreamErr.WriteRawError(w)
return
}
slog.Error("passthrough request failed", "endpoint", endpoint, "error", err)
WriteOpenAIError(w, http.StatusInternalServerError, OpenAIErrorTypeServerError, "Internal server error")
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(respData)
}
// doNonStreamingRequest makes a non-streaming request to the Copilot API via the shared upstream client.
func (h *Handler) doNonStreamingRequest(r *http.Request, endpoint string) ([]byte, error) {
var body interface{}
if r.Body != nil {
body = r.Body
}
_, respData, err := h.upstream.Do(r.Context(), upstream.Request{
Method: r.Method,
Endpoint: endpoint,
Body: body,
QueryString: r.URL.RawQuery,
ExtraHeaders: collectForwardHeaders(r),
})
return respData, err
}
// collectForwardHeaders returns headers from the original request that should be
// forwarded to the upstream API.
func collectForwardHeaders(r *http.Request) map[string]string {
headers := make(map[string]string)
for _, name := range []string{"Content-Type", "Accept", "Cache-Control"} {
if v := r.Header.Get(name); v != "" {
headers[name] = v
}
}
return headers
}
// handleUsage returns usage/quota info from the Copilot token response
func (h *Handler) HandleUsage(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
WriteOpenAIError(w, http.StatusMethodNotAllowed, OpenAIErrorTypeInvalidRequest, "Method not allowed")
return
}
usage, err := h.authClient.GetUsageInfo(r.Context())
if err != nil {
slog.Error("failed to get usage info", "error", err)
WriteOpenAIError(w, http.StatusInternalServerError, OpenAIErrorTypeServerError, "Failed to get usage info")
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(usage)
}
// handleEmbeddings normalizes input to array format before proxying
func (h *Handler) handleEmbeddings(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 10<<20) // 10MB limit
body, err := io.ReadAll(r.Body)
if err != nil {
WriteOpenAIError(w, http.StatusBadRequest, OpenAIErrorTypeInvalidRequest, "Failed to read request body")
return
}
var req map[string]json.RawMessage
if err := json.Unmarshal(body, &req); err != nil {
WriteOpenAIError(w, http.StatusBadRequest, OpenAIErrorTypeInvalidRequest, "Invalid JSON")
return
}
// If input is a string, wrap it in an array
if input, ok := req["input"]; ok {
var s string
if json.Unmarshal(input, &s) == nil {
wrapped, _ := json.Marshal([]string{s})
req["input"] = wrapped
body, _ = json.Marshal(req)
}
}
r.Body = io.NopCloser(bytes.NewReader(body))
r.ContentLength = int64(len(body))
h.handlePassthroughBody(w, r, "/embeddings", body)
}
// --- OpenAI error response helpers ---
// OpenAIErrorResponse represents an error response in OpenAI API format
type OpenAIErrorResponse struct {
Error OpenAIError `json:"error"`
}
// OpenAIError represents the error object in OpenAI API responses
type OpenAIError struct {
Message string `json:"message"`
Type string `json:"type"`
Code string `json:"code,omitempty"`
}
// Error type constants for OpenAI API
const (
OpenAIErrorTypeServerError = "server_error"
OpenAIErrorTypeInvalidRequest = "invalid_request_error"
)
// WriteOpenAIError writes an error response in OpenAI API format
func WriteOpenAIError(w http.ResponseWriter, statusCode int, errorType, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
errorResp := OpenAIErrorResponse{
Error: OpenAIError{
Message: message,
Type: errorType,
},
}
json.NewEncoder(w).Encode(errorResp)
}