-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathhttp.ts
More file actions
428 lines (356 loc) · 11.7 KB
/
http.ts
File metadata and controls
428 lines (356 loc) · 11.7 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
import { showCreditsToast } from '@/components/Toast/creditsToast';
import { showStorageToast } from '@/components/Toast/storageToast';
import { showTrafficToast } from '@/components/Toast/trafficToast';
import { getAuthStore } from '@/store/authStore';
const defaultHeaders = {
'Content-Type': 'application/json',
};
let baseUrl = '';
export async function getBaseURL() {
if (baseUrl) {
return baseUrl;
}
const port = await window.ipcRenderer.invoke('get-backend-port');
baseUrl = `http://localhost:${port}`;
return baseUrl;
}
async function fetchRequest(
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
url: string,
data?: Record<string, any>,
customHeaders: Record<string, string> = {}
): Promise<any> {
const baseURL = await getBaseURL();
const fullUrl = `${baseURL}${url}`;
const { token } = getAuthStore();
const headers: Record<string, string> = {
...defaultHeaders,
...customHeaders,
};
// Cases without token: url is a complete http:// path
if (!url.includes('http://') && token) {
headers['Authorization'] = `Bearer ${token}`;
}
const options: RequestInit = {
method,
headers,
};
if (method === 'GET') {
const query = data
? '?' +
Object.entries(data)
.map(
([key, val]) =>
`${encodeURIComponent(key)}=${encodeURIComponent(val)}`
)
.join('&')
: '';
return handleResponse(fetch(fullUrl + query, options), data);
}
if (data) {
options.body = JSON.stringify(data);
}
return handleResponse(fetch(fullUrl, options), data);
}
async function handleResponse(
responsePromise: Promise<Response>,
requestData?: Record<string, any>
): Promise<any> {
try {
const res = await responsePromise;
if (res.status === 204) {
return { code: 0, text: '' };
}
const contentType = res.headers.get('content-type') || '';
if (res.body && !contentType.includes('application/json')) {
return {
isStream: true,
body: res.body,
reader: res.body.getReader(),
};
}
const resData = await res.json();
if (!resData) {
return null;
}
const { code, text } = resData;
// showCreditsToast()
if (code === 1 || code === 300) {
return resData;
}
if (code === 20) {
showCreditsToast();
return resData;
}
if (code === 21) {
showStorageToast();
return resData;
}
if (code === 13) {
// const { logout } = getAuthStore()
// logout()
// window.location.href = '#/login'
throw new Error(text);
}
if (!res.ok) {
const err: any = new Error(
resData?.detail || resData?.message || `HTTP error ${res.status}`
);
err.response = { data: resData, status: res.status };
throw err;
}
return resData;
} catch (err: any) {
// Only show traffic toast for cloud model requests
const isCloudRequest = requestData?.api_url === 'cloud';
if (isCloudRequest) {
showTrafficToast();
}
console.error('[fetch error]:', err);
if (err?.response?.status === 401) {
// const { logout } = getAuthStore()
// logout()
// window.location.href = '#/login'
}
throw err;
}
}
// Encapsulate common methods
export const fetchGet = (url: string, params?: any, headers?: any) =>
fetchRequest('GET', url, params, headers);
export const fetchPost = (url: string, data?: any, headers?: any) =>
fetchRequest('POST', url, data, headers);
export const fetchPut = (url: string, data?: any, headers?: any) =>
fetchRequest('PUT', url, data, headers);
export const fetchDelete = (url: string, data?: any, headers?: any) =>
fetchRequest('DELETE', url, data, headers);
// =============== porxy ===============
// get proxy base URL
async function getProxyBaseURL() {
const isDev = import.meta.env.DEV;
if (isDev) {
const proxyUrl = import.meta.env.VITE_PROXY_URL;
if (!proxyUrl) {
return 'http://localhost:3001';
}
return proxyUrl;
} else {
const baseUrl = import.meta.env.VITE_BASE_URL;
if (!baseUrl) {
throw new Error('VITE_BASE_URL not configured');
}
return baseUrl;
}
}
async function proxyFetchRequest(
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
url: string,
data?: Record<string, any>,
customHeaders: Record<string, string> = {}
): Promise<any> {
const baseURL = await getProxyBaseURL();
const fullUrl = `${baseURL}${url}`;
const { token } = getAuthStore();
const headers: Record<string, string> = {
...defaultHeaders,
...customHeaders,
};
if (!url.includes('http://') && !url.includes('https://') && token) {
headers['Authorization'] = `Bearer ${token}`;
}
if (import.meta.env.DEV) {
const targetUrl = import.meta.env.VITE_BASE_URL;
if (targetUrl) {
headers['X-Proxy-Target'] = targetUrl;
}
}
const options: RequestInit = {
method,
headers,
};
if (method === 'GET') {
const query = data
? '?' +
Object.entries(data)
.map(
([key, val]) =>
`${encodeURIComponent(key)}=${encodeURIComponent(val)}`
)
.join('&')
: '';
return handleResponse(fetch(fullUrl + query, options));
}
if (data) {
options.body = JSON.stringify(data);
}
return handleResponse(fetch(fullUrl, options));
}
export const proxyFetchGet = (url: string, params?: any, headers?: any) =>
proxyFetchRequest('GET', url, params, headers);
export const proxyFetchPost = (url: string, data?: any, headers?: any) =>
proxyFetchRequest('POST', url, data, headers);
export const proxyFetchPut = (url: string, data?: any, headers?: any) =>
proxyFetchRequest('PUT', url, data, headers);
export const proxyFetchPatch = (url: string, data?: any, headers?: any) =>
proxyFetchRequest('PATCH', url, data, headers);
export const proxyFetchDelete = (url: string, data?: any, headers?: any) =>
proxyFetchRequest('DELETE', url, data, headers);
// File upload function with FormData
export async function uploadFile(
url: string,
formData: FormData,
headers?: Record<string, string>
): Promise<any> {
const baseURL = await getProxyBaseURL();
const fullUrl = `${baseURL}${url}`;
const { token } = getAuthStore();
const requestHeaders: Record<string, string> = {
...headers,
};
// Remove Content-Type header to let browser set it with boundary for FormData
if (requestHeaders['Content-Type']) {
delete requestHeaders['Content-Type'];
}
if (!url.includes('http://') && !url.includes('https://') && token) {
requestHeaders['Authorization'] = `Bearer ${token}`;
}
if (import.meta.env.DEV) {
const targetUrl = import.meta.env.VITE_BASE_URL;
if (targetUrl) {
requestHeaders['X-Proxy-Target'] = targetUrl;
}
}
const options: RequestInit = {
method: 'POST',
headers: requestHeaders,
body: formData,
};
return handleResponse(fetch(fullUrl, options));
}
// =============== Backend Health Check ===============
/**
* Check if backend is ready by checking the health endpoint
* @returns Promise<boolean> - true if backend is ready, false otherwise
*/
export async function checkBackendHealth(): Promise<boolean> {
try {
const baseURL = await getBaseURL();
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 1000);
const res = await fetch(`${baseURL}/health`, {
signal: controller.signal,
method: 'GET',
});
clearTimeout(timeoutId);
return res.ok;
} catch (error) {
console.log('[Backend Health Check] Not ready:', error);
return false;
}
}
// =============== Local Server Stale Detection ===============
/**
* Git hash of the last commit that touched server/, injected by Vite at build
* time. When the running server reports a different hash it means the server
* process is stale and needs to be restarted / rebuilt.
*/
const EXPECTED_SERVER_HASH: string =
import.meta.env.VITE_SERVER_CODE_HASH || '';
let serverStaleChecked = false;
/**
* One-time check: when VITE_USE_LOCAL_PROXY is enabled, fetch the local
* server's /health and compare its server_hash against the expected hash
* baked into this build. Shows a persistent toast if they differ.
*/
export async function checkLocalServerStale(): Promise<void> {
if (serverStaleChecked || !EXPECTED_SERVER_HASH) return;
serverStaleChecked = true;
const useLocalProxy = import.meta.env.VITE_USE_LOCAL_PROXY === 'true';
if (!useLocalProxy) return;
const serverUrl = import.meta.env.VITE_PROXY_URL || 'http://localhost:3001';
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 3000);
const res = await fetch(`${serverUrl}/health`, {
signal: controller.signal,
method: 'GET',
});
clearTimeout(timeoutId);
let staleReason = '';
if (res.status === 404) {
// /health endpoint doesn't exist — server predates v0.0.89
staleReason = 'Server does not have /health endpoint (pre-v0.0.89)';
} else if (res.ok) {
const data = await res.json();
const serverHash: string | undefined = data?.server_hash;
if (!serverHash) {
staleReason = 'Server does not report version info (pre-v0.0.89)';
} else if (
serverHash !== 'unknown' &&
serverHash !== EXPECTED_SERVER_HASH
) {
staleReason = `Server hash ${serverHash} != expected ${EXPECTED_SERVER_HASH}`;
}
} else {
// Other HTTP errors — skip
return;
}
if (staleReason) {
const { toast } = await import('sonner');
toast.warning('Server code has been updated', {
description:
'Server is outdated. Please restart it or rebuild: docker-compose up --build -d',
duration: Infinity,
closeButton: true,
});
console.warn(`[Server Check] ${staleReason}. Please restart the server.`);
}
} catch {
// server not reachable — skip silently
}
}
/**
* Simple backend health check with retries
* @param maxWaitMs - Maximum time to wait in milliseconds (default: 10000ms)
* @param retryIntervalMs - Interval between retries in milliseconds (default: 500ms)
* @returns Promise<boolean> - true if backend becomes ready, false if timeout
*/
export async function waitForBackendReady(
maxWaitMs: number = 10000,
retryIntervalMs: number = 500
): Promise<boolean> {
const startTime = Date.now();
console.log('[Backend Health Check] Waiting for backend to be ready...');
while (Date.now() - startTime < maxWaitMs) {
const isReady = await checkBackendHealth();
if (isReady) {
console.log(
`[Backend Health Check] Backend is ready after ${Date.now() - startTime}ms`
);
// Fire-and-forget: check local server version when using local proxy
checkLocalServerStale();
return true;
}
console.log(
`[Backend Health Check] Backend not ready, retrying... (${Date.now() - startTime}ms elapsed)`
);
await new Promise((resolve) => setTimeout(resolve, retryIntervalMs));
}
console.error(
`[Backend Health Check] Backend failed to start within ${maxWaitMs}ms`
);
return false;
}