client.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. /** BFF API 客户端 + SSE 解析。 */
  2. import type {
  3. ChatMessage,
  4. DataObject,
  5. HealthPayload,
  6. PreviewPayload,
  7. RunInfo,
  8. Session,
  9. Workspace,
  10. } from './types';
  11. const BASE = import.meta.env.VITE_API_BASE ?? '';
  12. export class ApiError extends Error {
  13. constructor(readonly status: number, message: string, readonly detail?: unknown) {
  14. super(message);
  15. this.name = 'ApiError';
  16. }
  17. }
  18. async function request<T>(path: string, init?: RequestInit): Promise<T> {
  19. const response = await fetch(`${BASE}${path}`, init);
  20. const text = await response.text();
  21. let payload: any = null;
  22. try {
  23. payload = text ? JSON.parse(text) : null;
  24. } catch {
  25. payload = text;
  26. }
  27. if (!response.ok) {
  28. const message = payload?.message ?? payload?.detail ?? `请求失败(HTTP ${response.status})`;
  29. throw new ApiError(response.status, String(message), payload);
  30. }
  31. return payload as T;
  32. }
  33. function jsonInit(method: string, body: unknown): RequestInit {
  34. return {
  35. method,
  36. headers: { 'Content-Type': 'application/json' },
  37. body: JSON.stringify(body),
  38. };
  39. }
  40. export const api = {
  41. health: () => request<HealthPayload>('/api/health'),
  42. meta: () => request<Record<string, any>>('/api/meta'),
  43. listWorkspaces: () => request<{ items: Workspace[] }>('/api/workspaces'),
  44. createWorkspace: (name: string, description = '') =>
  45. request<Workspace>('/api/workspaces', jsonInit('POST', { name, description })),
  46. deleteWorkspace: (id: string) => request<{ ok: boolean }>(`/api/workspaces/${id}`, { method: 'DELETE' }),
  47. listFiles: (workspaceId: string, kind?: string) =>
  48. request<{ items: DataObject[] }>(`/api/workspaces/${workspaceId}/files${kind ? `?kind=${kind}` : ''}`),
  49. uploadFile: async (workspaceId: string, file: File, onProgress?: (percent: number) => void) => {
  50. // 用 XHR 才能拿到上传进度(fetch 不支持)
  51. return new Promise<DataObject>((resolve, reject) => {
  52. const xhr = new XMLHttpRequest();
  53. xhr.open('POST', `${BASE}/api/workspaces/${workspaceId}/files`);
  54. xhr.setRequestHeader('Content-Type', 'application/octet-stream');
  55. xhr.setRequestHeader('X-Filename', encodeURIComponent(file.name));
  56. xhr.upload.onprogress = (event) => {
  57. if (event.lengthComputable && onProgress) onProgress(Math.round((event.loaded / event.total) * 100));
  58. };
  59. xhr.onload = () => {
  60. if (xhr.status >= 200 && xhr.status < 300) {
  61. try {
  62. resolve(JSON.parse(xhr.responseText) as DataObject);
  63. } catch (error) {
  64. reject(new ApiError(500, '返回内容不是 JSON'));
  65. }
  66. return;
  67. }
  68. let message = `上传失败(HTTP ${xhr.status})`;
  69. try {
  70. const parsed = JSON.parse(xhr.responseText);
  71. message = parsed.message ?? parsed.detail ?? message;
  72. } catch {
  73. /* 忽略 */
  74. }
  75. reject(new ApiError(xhr.status, message));
  76. };
  77. xhr.onerror = () => reject(new ApiError(0, '网络错误:无法连接 BFF'));
  78. xhr.send(file);
  79. });
  80. },
  81. getObject: (objectId: string) => request<DataObject>(`/api/objects/${objectId}`),
  82. deleteObject: (objectId: string) => request<{ ok: boolean }>(`/api/objects/${objectId}`, { method: 'DELETE' }),
  83. preview: (objectId: string, table: string, limit = 20, offset = 0) =>
  84. request<PreviewPayload>(
  85. `/api/objects/${objectId}/preview?table=${encodeURIComponent(table)}&limit=${limit}&offset=${offset}`,
  86. ),
  87. lineage: (objectId: string, table: string, row: number) =>
  88. request<Record<string, unknown>>(`/api/objects/${objectId}/lineage?table=${encodeURIComponent(table)}&row=${row}`),
  89. downloadUrl: (objectId: string, name: string) =>
  90. `${BASE}/api/objects/${objectId}/download?name=${encodeURIComponent(name)}`,
  91. /** 打包下载一次处理的全部结果文件(Excel + 逐表 CSV + 明细)。 */
  92. archiveUrl: (objectId: string, include: 'all' | 'xlsx' | 'csv' = 'all') =>
  93. `${BASE}/api/objects/${objectId}/archive?include=${include}`,
  94. startProcess: (payload: {
  95. workspace_id: string;
  96. input_object_id: string;
  97. operation?: string;
  98. options?: Record<string, unknown>;
  99. output_name?: string;
  100. }) => request<RunInfo>('/api/process', jsonInit('POST', payload)),
  101. getRun: (runId: string) => request<RunInfo>(`/api/process/${runId}`),
  102. listRuns: () => request<{ items: RunInfo[] }>('/api/process'),
  103. /** 处理进度 SSE:返回取消函数 */
  104. streamRun(runId: string, handlers: { onProgress(run: any): void; onDone(run: any): void; onError(error: Error): void }): () => void {
  105. const controller = new AbortController();
  106. (async () => {
  107. try {
  108. const response = await fetch(`${BASE}/api/process/${runId}/stream`, { signal: controller.signal });
  109. if (!response.ok || !response.body) throw new ApiError(response.status, `进度流打开失败(HTTP ${response.status})`);
  110. await consumeSse(response.body, {
  111. onEvent(event, data) {
  112. if (event === 'progress') handlers.onProgress(data);
  113. else if (event === 'done') handlers.onDone(data);
  114. else if (event === 'error') handlers.onError(new ApiError(500, data.message ?? '进度流出错'));
  115. },
  116. onError: handlers.onError,
  117. onClose: () => undefined,
  118. }, controller.signal);
  119. } catch (error) {
  120. if ((error as Error).name !== 'AbortError') handlers.onError(error as Error);
  121. }
  122. })();
  123. return () => controller.abort();
  124. },
  125. /** 按行号取一行(溯源抽屉) */
  126. objectRow: (objectId: string, table: string, row: number) =>
  127. request<Record<string, any>>(`/api/objects/${objectId}/row?table=${encodeURIComponent(table)}&row=${row}`),
  128. /** 会话台账里某次调用的详情(calculator chip 用) */
  129. sessionLedgerCall: (sessionId: string, callId: string) =>
  130. request<Record<string, any>>(`/api/sessions/${sessionId}/ledger/${encodeURIComponent(callId)}`),
  131. listSessions: (workspaceId?: string) =>
  132. request<{ items: Session[] }>(`/api/sessions${workspaceId ? `?workspace_id=${workspaceId}` : ''}`),
  133. createSession: (workspaceId: string, title?: string) =>
  134. request<Session>('/api/sessions', jsonInit('POST', { workspace_id: workspaceId, title })),
  135. listMessages: (sessionId: string) =>
  136. request<{ session: Session; items: ChatMessage[] }>(`/api/sessions/${sessionId}/messages`),
  137. renameSession: (sessionId: string, title: string) =>
  138. request<Session>(`/api/sessions/${sessionId}`, jsonInit('PUT', { title })),
  139. deleteSession: (sessionId: string) => request<{ ok: boolean }>(`/api/sessions/${sessionId}`, { method: 'DELETE' }),
  140. sessionLedger: (sessionId: string) => request<Record<string, any>>(`/api/sessions/${sessionId}/ledger`),
  141. verifications: (sessionId: string) => request<{ items: any[] }>(`/api/system/verifications?session_id=${sessionId}`),
  142. };
  143. // ------------------------------------------------------------------ SSE
  144. export interface ChatStreamHandlers {
  145. onEvent(event: string, data: any): void;
  146. onError(error: Error): void;
  147. onClose(): void;
  148. }
  149. /**
  150. * 发送消息并消费 SSE。返回 abort 函数。
  151. * 用 fetch + ReadableStream 而不是 EventSource(EventSource 只能 GET)。
  152. */
  153. export function streamChat(sessionId: string, message: string, handlers: ChatStreamHandlers): () => void {
  154. const controller = new AbortController();
  155. (async () => {
  156. try {
  157. const response = await fetch(`${BASE}/api/sessions/${sessionId}/chat`, {
  158. method: 'POST',
  159. headers: { 'Content-Type': 'application/json' },
  160. body: JSON.stringify({ message }),
  161. signal: controller.signal,
  162. });
  163. if (!response.ok) {
  164. const text = await response.text();
  165. let detail = text;
  166. try {
  167. detail = JSON.parse(text).message ?? text;
  168. } catch {
  169. /* 保留原文 */
  170. }
  171. throw new ApiError(response.status, detail);
  172. }
  173. if (!response.body) throw new ApiError(500, '服务端没有返回流');
  174. await consumeSse(response.body, handlers, controller.signal);
  175. } catch (error) {
  176. if ((error as Error).name === 'AbortError') {
  177. handlers.onClose();
  178. return;
  179. }
  180. handlers.onError(error as Error);
  181. }
  182. })();
  183. return () => controller.abort();
  184. }
  185. /** 逐块解析 SSE(text/event-stream),支持多行 data。 */
  186. export async function consumeSse(
  187. body: ReadableStream<Uint8Array>,
  188. handlers: ChatStreamHandlers,
  189. signal?: AbortSignal,
  190. ): Promise<void> {
  191. const reader = body.getReader();
  192. const decoder = new TextDecoder();
  193. let buffer = '';
  194. try {
  195. for (;;) {
  196. if (signal?.aborted) break;
  197. const { done, value } = await reader.read();
  198. if (done) break;
  199. buffer += decoder.decode(value, { stream: true });
  200. let boundary = buffer.indexOf('\n\n');
  201. while (boundary >= 0) {
  202. const block = buffer.slice(0, boundary);
  203. buffer = buffer.slice(boundary + 2);
  204. boundary = buffer.indexOf('\n\n');
  205. const parsed = parseEventBlock(block);
  206. if (parsed) handlers.onEvent(parsed.event, parsed.data);
  207. }
  208. }
  209. const tail = parseEventBlock(buffer);
  210. if (tail) handlers.onEvent(tail.event, tail.data);
  211. handlers.onClose();
  212. } finally {
  213. reader.releaseLock();
  214. }
  215. }
  216. export function parseEventBlock(block: string): { event: string; data: any } | null {
  217. const lines = block.split('\n');
  218. let event = 'message';
  219. const dataLines: string[] = [];
  220. for (const line of lines) {
  221. if (line.startsWith(':')) continue;
  222. if (line.startsWith('event:')) event = line.slice(6).trim();
  223. else if (line.startsWith('data:')) dataLines.push(line.slice(5).trim());
  224. }
  225. if (dataLines.length === 0) return null;
  226. const raw = dataLines.join('\n');
  227. try {
  228. return { event, data: JSON.parse(raw) };
  229. } catch {
  230. return { event, data: raw };
  231. }
  232. }