api.ts
9.67 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
import type {
Job,
ServerConfigView,
GenerateRequest,
GenerateResponse,
PreviewState,
LogEntry,
SystemStatus,
ProjectProfile,
FsListResult,
ProjectRunState,
} from './types';
// 同源调用:开发时由 Vite 代理到后端 :4173;生产时后端直接托管本应用。
const BASE = '';
// 后端重启宽限期:重启后短时间内,网络错误/5xx 属「后端短暂不可用」,
// http() 会静默重试,避免重启窗口期弹出一堆「请求失败」。宽限期外仍照常报错。
let backendRestartingUntil = 0;
export function markBackendRestarting(cooldownMs = 9000): void {
backendRestartingUntil = Date.now() + cooldownMs;
}
// 后端被「有意停止」标记:此时常规 /api 请求经 Vite 代理会得到 5xx/连接错误,
// 我们把它标记为非意外错误,避免刷「请求失败」;同时 UI 据此显示「已停止」状态。
let backendKnownDown = false;
export function setBackendKnownDown(v: boolean): void {
backendKnownDown = v;
}
export function isBackendDownError(e: unknown): boolean {
return (e as { expectedDown?: boolean })?.expectedDown === true;
}
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
async function httpOnce<T>(path: string, init?: RequestInit): Promise<T> {
let res: Response;
try {
res = await fetch(BASE + path, {
...init,
headers: { 'Content-Type': 'application/json', ...(init?.headers ?? {}) },
});
} catch (e) {
// 网络层错误(后端已停止,代理连不上)。已知后端被有意停止时标记为非意外错误。
if (backendKnownDown && path.startsWith('/api')) {
throw Object.assign(new Error('后端未运行'), { status: 0, expectedDown: true });
}
throw e;
}
const text = await res.text();
const data = text ? JSON.parse(text) : null;
if (!res.ok) {
const err = Object.assign(new Error(data?.error || `请求失败 (${res.status})`), {
status: res.status,
});
// 后端被有意停止时,常规 /api 请求会经 Vite 代理得到 5xx,标记为非意外错误。
if (backendKnownDown && path.startsWith('/api') && res.status >= 500) {
(err as { expectedDown?: boolean }).expectedDown = true;
}
throw err;
}
return data as T;
}
async function http<T>(path: string, init?: RequestInit): Promise<T> {
if (Date.now() < backendRestartingUntil) {
let lastErr: unknown;
for (let i = 0; i < 12; i++) {
try {
return await httpOnce<T>(path, init);
} catch (e) {
const status = (e as { status?: number })?.status;
// 仅对「网络错误(status 缺失) / 5xx」重试;业务 4xx 立即抛出。
lastErr = e;
if (status != null && status < 500) throw e;
await sleep(400);
}
}
throw lastErr;
}
return httpOnce<T>(path, init);
}
export const api = {
getConfig: () => http<ServerConfigView>('/api/config'),
generate: (req: GenerateRequest) =>
http<GenerateResponse>('/api/generate', {
method: 'POST',
body: JSON.stringify(req),
}),
listJobs: () => http<{ jobs: Job[] }>('/api/jobs'),
getJob: (id: string) => http<Job>(`/api/job/${id}`),
getLogs: () => http<{ logs: LogEntry[] }>('/api/logs'),
cancelJob: (id: string) =>
http<{ ok: boolean }>(`/api/jobs/${id}/cancel`, { method: 'POST' }),
deleteJob: (id: string) =>
http<{ ok: boolean }>(`/api/jobs/${id}`, { method: 'DELETE' }),
clearJobs: () =>
http<{ ok: boolean; count: number }>('/api/jobs', { method: 'DELETE' }),
getPreview: () => http<PreviewState>('/api/preview'),
startPreview: (appPath?: string) =>
http<{ ok: boolean; error?: string }>('/api/preview', {
method: 'POST',
body: JSON.stringify({ appPath }),
}),
stopPreview: () =>
http<{ ok: boolean }>('/api/preview/stop', { method: 'POST' }),
restartPreview: () =>
http<{ ok: boolean; error?: string }>('/api/preview/restart', { method: 'POST' }),
getStatus: () => http<SystemStatus>('/api/admin/status'),
restartServer: () =>
http<{ ok: boolean }>('/api/admin/restart', { method: 'POST' }),
shutdownServer: () =>
http<{ ok: boolean }>('/api/admin/shutdown', { method: 'POST' }),
getProjectProfile: () =>
http<{ exists: boolean; profile: ProjectProfile }>('/api/project-profile'),
putProjectProfile: (profile: ProjectProfile) =>
http<{ ok: boolean; profile: ProjectProfile }>('/api/project-profile', {
method: 'PUT',
body: JSON.stringify(profile),
}),
scanProjectProfile: (rootDir: string) =>
http<{ profile: ProjectProfile; pages: string[]; warnings: string[] }>(
'/api/project-profile/scan',
{ method: 'POST', body: JSON.stringify({ rootDir }) },
),
fsList: (dir?: string) =>
http<FsListResult>(
'/api/fs/list' + (dir ? `?dir=${encodeURIComponent(dir)}` : ''),
),
getProjectRun: () => http<ProjectRunState>('/api/project/run'),
startProject: (dir: string) =>
http<{ ok: boolean; error?: string }>('/api/project/run', {
method: 'POST',
body: JSON.stringify({ dir }),
}),
stopProject: () =>
http<{ ok: boolean }>('/api/project/run/stop', { method: 'POST' }),
// ---- 后端生命周期(由开发模式 supervisor 管理,见 scripts/dev.mjs)----
// 这些请求走 /devctl 代理到 supervisor(4174),supervisor 常驻,即使后端已停止
// 也能接收启动指令。生产单进程模式无 supervisor,这些调用会失败。
backendStatus: () => http<{ running: boolean }>('/devctl/backend/status'),
startBackend: () =>
http<{ ok: boolean }>('/devctl/backend/start', { method: 'POST' }),
stopBackend: () =>
http<{ ok: boolean }>('/devctl/backend/stop', { method: 'POST' }),
restartBackend: () =>
http<{ ok: boolean }>('/devctl/backend/restart', { method: 'POST' }),
// 停止全部:请求 supervisor 自杀式退出(连同前端 Vite 与后端一起回收)。
// 仅开发模式(supervisor 常驻)可用;之后需重新运行 npm run dev 启动。
shutdownDev: () =>
http<{ ok: boolean }>('/devctl/shutdown', { method: 'POST' }),
// ---- 本地模型 (Ollama):经后端转发,进度走 SSE "ollama" 事件 ----
ollamaStatus: () => http<OllamaStatus>('/api/ollama/status'),
listOllamaModels: () =>
http<{ models: OllamaModel[]; error?: string }>('/api/ollama/models'),
connectOllama: (model: string) =>
http<{ ok: true; activeModel: string }>('/api/ollama/connect', {
method: 'POST',
body: JSON.stringify({ model }),
}),
disconnectOllama: () =>
http<{ ok: true }>('/api/ollama/disconnect', { method: 'POST' }),
pullOllamaModel: (model: string) =>
http<{ accepted: true; model: string }>('/api/ollama/pull', {
method: 'POST',
body: JSON.stringify({ model }),
}),
};
/**
* 直接探测后端就绪状态(不走 http() 的重试/冷却机制,静默吞掉网络错误)。
* 后端端口仅在引擎加载 + sqlite 初始化完成后才 listen(),故本调用返回 true
* 即代表后端已完全就绪、可安全发起 /api/generate。用于「重启后端」boot 窗口期
* 门控「开始生成」按钮,避免点进尚未就绪的端口报 ECONNREFUSED。
*/
export async function checkBackendHealth(): Promise<boolean> {
try {
const res = await fetch(BASE + '/api/health', {
headers: { 'Content-Type': 'application/json' },
});
// 只要后端回了任何 HTTP 响应(含 404,来自尚未升级的旧后端)即说明端口已开、
// 后端已就绪,可安全发起 /api/generate;仅网络层错误(端口未开 / ECONNREFUSED)
// 代表后端仍在 boot 中。这样对「旧后端(无 /api/health)」也向后兼容。
return res.status < 500;
} catch {
return false;
}
}
export type SSEEventName = 'log' | 'jobs' | 'preview' | 'projectRun' | 'system' | string;
// 全局单例 SSE 连接:整个应用只建立一条 /api/stream,所有组件通过 onSSE 订阅
// 特定事件。避免每个组件各开一条连接、也彻底消除「前端用 setInterval 轮询后端状态」的刷屏。
// 后端在状态变化时通过 hub.broadcast 推送(jobs / preview / projectRun 等),SSE 连接建立时
// 还会 replay 一次当前快照(见 server.ts 的 /api/stream 处理)。
let sseInstance: EventSource | null = null;
const sseEventSubs = new Map<SSEEventName, Set<(data: unknown) => void>>();
const sseOpenSubs = new Set<() => void>();
const sseCloseSubs = new Set<() => void>();
const SSE_EVENTS: SSEEventName[] = ['log', 'jobs', 'preview', 'projectRun', 'system', 'ollama'];
function ensureSSE(): EventSource {
if (sseInstance) return sseInstance;
const es = new EventSource('/api/stream');
for (const name of SSE_EVENTS) {
es.addEventListener(name, (e: MessageEvent) => {
try {
const data = JSON.parse(e.data);
sseEventSubs.get(name)?.forEach((h) => h(data));
} catch {
/* ignore malformed */
}
});
}
es.onopen = () => sseOpenSubs.forEach((f) => f());
es.onerror = () => sseCloseSubs.forEach((f) => f());
sseInstance = es;
return es;
}
/** 订阅某个 SSE 事件,返回取消订阅函数。 */
export function onSSE(
event: SSEEventName,
handler: (data: unknown) => void,
): () => void {
ensureSSE();
if (!sseEventSubs.has(event)) sseEventSubs.set(event, new Set());
sseEventSubs.get(event)!.add(handler);
return () => {
sseEventSubs.get(event)?.delete(handler);
};
}
/** 订阅 SSE 连接状态变化(打开 / 关闭),返回取消订阅函数。 */
export function onSSEStatus(
onOpen: () => void,
onClose: () => void,
): () => void {
ensureSSE();
sseOpenSubs.add(onOpen);
sseCloseSubs.add(onClose);
return () => {
sseOpenSubs.delete(onOpen);
sseCloseSubs.delete(onClose);
};
}
export type { LogEntry, Job };