| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247 |
- /** BFF API 客户端 + SSE 解析。 */
- import type {
- ChatMessage,
- DataObject,
- HealthPayload,
- PreviewPayload,
- RunInfo,
- Session,
- Workspace,
- } from './types';
- const BASE = import.meta.env.VITE_API_BASE ?? '';
- export class ApiError extends Error {
- constructor(readonly status: number, message: string, readonly detail?: unknown) {
- super(message);
- this.name = 'ApiError';
- }
- }
- async function request<T>(path: string, init?: RequestInit): Promise<T> {
- const response = await fetch(`${BASE}${path}`, init);
- const text = await response.text();
- let payload: any = null;
- try {
- payload = text ? JSON.parse(text) : null;
- } catch {
- payload = text;
- }
- if (!response.ok) {
- const message = payload?.message ?? payload?.detail ?? `请求失败(HTTP ${response.status})`;
- throw new ApiError(response.status, String(message), payload);
- }
- return payload as T;
- }
- function jsonInit(method: string, body: unknown): RequestInit {
- return {
- method,
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(body),
- };
- }
- export const api = {
- health: () => request<HealthPayload>('/api/health'),
- meta: () => request<Record<string, any>>('/api/meta'),
- listWorkspaces: () => request<{ items: Workspace[] }>('/api/workspaces'),
- createWorkspace: (name: string, description = '') =>
- request<Workspace>('/api/workspaces', jsonInit('POST', { name, description })),
- deleteWorkspace: (id: string) => request<{ ok: boolean }>(`/api/workspaces/${id}`, { method: 'DELETE' }),
- listFiles: (workspaceId: string, kind?: string) =>
- request<{ items: DataObject[] }>(`/api/workspaces/${workspaceId}/files${kind ? `?kind=${kind}` : ''}`),
- uploadFile: async (workspaceId: string, file: File, onProgress?: (percent: number) => void) => {
- // 用 XHR 才能拿到上传进度(fetch 不支持)
- return new Promise<DataObject>((resolve, reject) => {
- const xhr = new XMLHttpRequest();
- xhr.open('POST', `${BASE}/api/workspaces/${workspaceId}/files`);
- xhr.setRequestHeader('Content-Type', 'application/octet-stream');
- xhr.setRequestHeader('X-Filename', encodeURIComponent(file.name));
- xhr.upload.onprogress = (event) => {
- if (event.lengthComputable && onProgress) onProgress(Math.round((event.loaded / event.total) * 100));
- };
- xhr.onload = () => {
- if (xhr.status >= 200 && xhr.status < 300) {
- try {
- resolve(JSON.parse(xhr.responseText) as DataObject);
- } catch (error) {
- reject(new ApiError(500, '返回内容不是 JSON'));
- }
- return;
- }
- let message = `上传失败(HTTP ${xhr.status})`;
- try {
- const parsed = JSON.parse(xhr.responseText);
- message = parsed.message ?? parsed.detail ?? message;
- } catch {
- /* 忽略 */
- }
- reject(new ApiError(xhr.status, message));
- };
- xhr.onerror = () => reject(new ApiError(0, '网络错误:无法连接 BFF'));
- xhr.send(file);
- });
- },
- getObject: (objectId: string) => request<DataObject>(`/api/objects/${objectId}`),
- deleteObject: (objectId: string) => request<{ ok: boolean }>(`/api/objects/${objectId}`, { method: 'DELETE' }),
- preview: (objectId: string, table: string, limit = 20, offset = 0) =>
- request<PreviewPayload>(
- `/api/objects/${objectId}/preview?table=${encodeURIComponent(table)}&limit=${limit}&offset=${offset}`,
- ),
- lineage: (objectId: string, table: string, row: number) =>
- request<Record<string, unknown>>(`/api/objects/${objectId}/lineage?table=${encodeURIComponent(table)}&row=${row}`),
- downloadUrl: (objectId: string, name: string) =>
- `${BASE}/api/objects/${objectId}/download?name=${encodeURIComponent(name)}`,
- /** 打包下载一次处理的全部结果文件(Excel + 逐表 CSV + 明细)。 */
- archiveUrl: (objectId: string, include: 'all' | 'xlsx' | 'csv' = 'all') =>
- `${BASE}/api/objects/${objectId}/archive?include=${include}`,
- startProcess: (payload: {
- workspace_id: string;
- input_object_id: string;
- operation?: string;
- options?: Record<string, unknown>;
- output_name?: string;
- }) => request<RunInfo>('/api/process', jsonInit('POST', payload)),
- getRun: (runId: string) => request<RunInfo>(`/api/process/${runId}`),
- listRuns: () => request<{ items: RunInfo[] }>('/api/process'),
- /** 处理进度 SSE:返回取消函数 */
- streamRun(runId: string, handlers: { onProgress(run: any): void; onDone(run: any): void; onError(error: Error): void }): () => void {
- const controller = new AbortController();
- (async () => {
- try {
- const response = await fetch(`${BASE}/api/process/${runId}/stream`, { signal: controller.signal });
- if (!response.ok || !response.body) throw new ApiError(response.status, `进度流打开失败(HTTP ${response.status})`);
- await consumeSse(response.body, {
- onEvent(event, data) {
- if (event === 'progress') handlers.onProgress(data);
- else if (event === 'done') handlers.onDone(data);
- else if (event === 'error') handlers.onError(new ApiError(500, data.message ?? '进度流出错'));
- },
- onError: handlers.onError,
- onClose: () => undefined,
- }, controller.signal);
- } catch (error) {
- if ((error as Error).name !== 'AbortError') handlers.onError(error as Error);
- }
- })();
- return () => controller.abort();
- },
- /** 按行号取一行(溯源抽屉) */
- objectRow: (objectId: string, table: string, row: number) =>
- request<Record<string, any>>(`/api/objects/${objectId}/row?table=${encodeURIComponent(table)}&row=${row}`),
- /** 会话台账里某次调用的详情(calculator chip 用) */
- sessionLedgerCall: (sessionId: string, callId: string) =>
- request<Record<string, any>>(`/api/sessions/${sessionId}/ledger/${encodeURIComponent(callId)}`),
- listSessions: (workspaceId?: string) =>
- request<{ items: Session[] }>(`/api/sessions${workspaceId ? `?workspace_id=${workspaceId}` : ''}`),
- createSession: (workspaceId: string, title?: string) =>
- request<Session>('/api/sessions', jsonInit('POST', { workspace_id: workspaceId, title })),
- listMessages: (sessionId: string) =>
- request<{ session: Session; items: ChatMessage[] }>(`/api/sessions/${sessionId}/messages`),
- renameSession: (sessionId: string, title: string) =>
- request<Session>(`/api/sessions/${sessionId}`, jsonInit('PUT', { title })),
- deleteSession: (sessionId: string) => request<{ ok: boolean }>(`/api/sessions/${sessionId}`, { method: 'DELETE' }),
- sessionLedger: (sessionId: string) => request<Record<string, any>>(`/api/sessions/${sessionId}/ledger`),
- verifications: (sessionId: string) => request<{ items: any[] }>(`/api/system/verifications?session_id=${sessionId}`),
- };
- // ------------------------------------------------------------------ SSE
- export interface ChatStreamHandlers {
- onEvent(event: string, data: any): void;
- onError(error: Error): void;
- onClose(): void;
- }
- /**
- * 发送消息并消费 SSE。返回 abort 函数。
- * 用 fetch + ReadableStream 而不是 EventSource(EventSource 只能 GET)。
- */
- export function streamChat(sessionId: string, message: string, handlers: ChatStreamHandlers): () => void {
- const controller = new AbortController();
- (async () => {
- try {
- const response = await fetch(`${BASE}/api/sessions/${sessionId}/chat`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ message }),
- signal: controller.signal,
- });
- if (!response.ok) {
- const text = await response.text();
- let detail = text;
- try {
- detail = JSON.parse(text).message ?? text;
- } catch {
- /* 保留原文 */
- }
- throw new ApiError(response.status, detail);
- }
- if (!response.body) throw new ApiError(500, '服务端没有返回流');
- await consumeSse(response.body, handlers, controller.signal);
- } catch (error) {
- if ((error as Error).name === 'AbortError') {
- handlers.onClose();
- return;
- }
- handlers.onError(error as Error);
- }
- })();
- return () => controller.abort();
- }
- /** 逐块解析 SSE(text/event-stream),支持多行 data。 */
- export async function consumeSse(
- body: ReadableStream<Uint8Array>,
- handlers: ChatStreamHandlers,
- signal?: AbortSignal,
- ): Promise<void> {
- const reader = body.getReader();
- const decoder = new TextDecoder();
- let buffer = '';
- try {
- for (;;) {
- if (signal?.aborted) break;
- const { done, value } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
- let boundary = buffer.indexOf('\n\n');
- while (boundary >= 0) {
- const block = buffer.slice(0, boundary);
- buffer = buffer.slice(boundary + 2);
- boundary = buffer.indexOf('\n\n');
- const parsed = parseEventBlock(block);
- if (parsed) handlers.onEvent(parsed.event, parsed.data);
- }
- }
- const tail = parseEventBlock(buffer);
- if (tail) handlers.onEvent(tail.event, tail.data);
- handlers.onClose();
- } finally {
- reader.releaseLock();
- }
- }
- export function parseEventBlock(block: string): { event: string; data: any } | null {
- const lines = block.split('\n');
- let event = 'message';
- const dataLines: string[] = [];
- for (const line of lines) {
- if (line.startsWith(':')) continue;
- if (line.startsWith('event:')) event = line.slice(6).trim();
- else if (line.startsWith('data:')) dataLines.push(line.slice(5).trim());
- }
- if (dataLines.length === 0) return null;
- const raw = dataLines.join('\n');
- try {
- return { event, data: JSON.parse(raw) };
- } catch {
- return { event, data: raw };
- }
- }
|