DataSourcePanel.tsx
14.2 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
import {
AlertTriangle, Database, Loader2, Plug, RefreshCw, ShieldCheck, Trash2,
} from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { api, ApiError } from "@/lib/api";
import { cn, formatTime } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import {
Badge, Card, CardHeader, Confirm, Empty, ErrorNote, Field, Modal, Progress, Spinner,
} from "@/components/ui";
import type { DataSource, JobItem } from "@/lib/types";
const BLANK = { name: "", ds_type: "mysql", host: "", port: 3306, db_name: "", username: "", password: "" };
export function DataSourcePanel({ selectedId, onSelect, onChanged }: {
selectedId: number | null;
onSelect: (id: number) => void;
onChanged: () => void;
}) {
const [items, setItems] = useState<DataSource[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [cryptoReady, setCryptoReady] = useState(true);
const [editing, setEditing] = useState<DataSource | null>(null);
const [creating, setCreating] = useState(false);
const [confirmDel, setConfirmDel] = useState<DataSource | null>(null);
const [busy, setBusy] = useState<number | null>(null);
const [job, setJob] = useState<{ dsId: number; item: JobItem | null } | null>(null);
const load = useCallback(() => {
api.datasources().then((d) => { setItems(d); setError(null); })
.catch((e) => setError(e instanceof Error ? e.message : String(e)));
api.sqlMeta().then((m) => setCryptoReady(m.crypto_ready)).catch(() => undefined);
}, []);
useEffect(load, [load]);
// 内省是后台任务,轮询它的进度。也可以走 /api/jobs/{id}/events 的 SSE,
// 但这里只需要一个进度条,轮询代码短得多。
const jobId = job?.item?.id ?? null;
const timer = useRef<number>();
useEffect(() => {
if (jobId === null) return;
const tick = async () => {
try {
const j = await api.job(jobId);
setJob((s) => (s ? { ...s, item: j } : s));
if (j.status === "done" || j.status === "failed") {
toast(j.status === "done" ? "ok" : "error",
j.status === "done" ? "内省完成" : "内省失败", j.message);
setJob(null);
load();
onChanged();
return; // 不再排下一次
}
} catch { /* 任务还没落库,下一轮再看 */ }
timer.current = window.setTimeout(tick, 1200);
};
timer.current = window.setTimeout(tick, 800);
return () => window.clearTimeout(timer.current);
}, [jobId, load, onChanged]);
const test = async (ds: DataSource) => {
setBusy(ds.id);
try {
const info = await api.testDatasource(ds.id);
toast(info.warning ? "warn" : "ok", `连接成功:${info.database}`,
info.warning ?? `${info.version},${info.table_count} 张表`);
load();
} catch (e) {
toast("error", "连接失败", e instanceof Error ? e.message : String(e));
load();
} finally { setBusy(null); }
};
const introspect = async (ds: DataSource, resample = false) => {
setBusy(ds.id);
try {
const { job_id } = await api.introspect(ds.id, resample);
const j = await api.job(job_id);
setJob({ dsId: ds.id, item: j });
toast("ok", "已开始内省", "抓表结构 + 采样枚举列,几百张表可能要几分钟");
} catch (e) {
toast("error", "内省启动失败", e instanceof Error ? e.message : String(e));
} finally { setBusy(null); }
};
const remove = async (ds: DataSource) => {
try {
await api.deleteDatasource(ds.id);
toast("ok", `已删除数据源「${ds.name}」`);
load();
onChanged();
} catch (e) {
toast("error", "删除失败", e instanceof Error ? e.message : String(e));
}
setConfirmDel(null);
};
if (error) return <ErrorNote onRetry={load}>{error}</ErrorNote>;
if (!items) return <Card className="p-4"><Spinner /></Card>;
return (
<div className="space-y-3">
{!cryptoReady && (
<div className="card flex items-start gap-2.5 border-warn/40 bg-warn/5 p-3">
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-warn" />
<div className="text-[13px] leading-relaxed">
<p className="font-medium">未配置 SECRET_KEY,暂时不能添加数据源。</p>
<p className="mt-0.5 text-muted">
业务库口令必须加密存储。请在 <code className="rounded bg-ink/[0.07] px-1">.env</code> 里加一行
<code className="mx-1 rounded bg-ink/[0.07] px-1">SECRET_KEY=(一串足够长的随机字符)</code>
后重启服务。
</p>
</div>
</div>
)}
<Card>
<CardHeader
title="数据源"
desc="建议使用只读账号连接业务库。口令加密存储,不会明文落库,也不会回显。"
right={
<button className="btn btn-primary btn-sm" disabled={!cryptoReady}
onClick={() => { setEditing({ ...BLANK } as unknown as DataSource); setCreating(true); }}>
<Database className="h-3.5 w-3.5" /> 新建
</button>
} />
{items.length === 0 ? (
<Empty icon={<Database className="h-6 w-6" />} title="还没有数据源"
desc="添加一个 MySQL 连接,做一次内省,就能开始用自然语言提问了。" />
) : (
<div className="divide-y divide-line">
{items.map((ds) => (
<div key={ds.id}
className={cn("px-4 py-3 transition-colors",
selectedId === ds.id ? "bg-brand/[0.04]" : "hover:bg-ink/[0.015]")}>
<div className="flex flex-col gap-2 sm:flex-row sm:items-start">
<button className="min-w-0 flex-1 text-left" onClick={() => onSelect(ds.id)}>
<span className="flex flex-wrap items-center gap-1.5">
<span className="truncate text-[13.5px] font-medium">{ds.name}</span>
{selectedId === ds.id && <Badge tone="bg-brand/10 text-brand">当前</Badge>}
{ds.status === "ok" && <Badge tone="bg-ok/10 text-ok">已连通</Badge>}
{ds.status === "error" && <Badge tone="bg-bad/10 text-bad">连接异常</Badge>}
{ds.status === "new" && <Badge tone="bg-warn/10 text-warn">未测试</Badge>}
{ds.read_only && (
<span title="按只读方式使用"><ShieldCheck className="h-3.5 w-3.5 text-ok" /></span>
)}
</span>
<span className="mt-0.5 block truncate font-mono text-[11.5px] text-muted">
{ds.username}@{ds.host}:{ds.port}/{ds.db_name}
</span>
<span className="mt-0.5 block text-[11.5px] text-muted">
{ds.last_introspect_at
? `上次内省 ${formatTime(ds.last_introspect_at)}`
: "还没有内省过 —— 内省一次才能开始提问"}
</span>
{ds.status === "error" && ds.last_error && (
<span className="mt-0.5 block truncate text-[11.5px] text-bad" title={ds.last_error}>
{ds.last_error}
</span>
)}
</button>
{/* 按钮成组靠右,小屏换行到下一行整体左对齐,不跟文字挤在一起 */}
<div className="flex shrink-0 flex-wrap items-center gap-1 sm:justify-end">
<button className="btn btn-sm" disabled={busy === ds.id}
onClick={() => test(ds)} title="测试连接是否可用">
{busy === ds.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
: <Plug className="h-3.5 w-3.5" />}
测试
</button>
<button className={cn("btn btn-sm", !ds.last_introspect_at && "btn-primary")}
disabled={busy === ds.id || !!job}
onClick={() => introspect(ds)} title="抓取表结构并采样枚举列">
<RefreshCw className="h-3.5 w-3.5" /> 内省
</button>
<button className="btn btn-ghost btn-sm"
onClick={() => { setEditing(ds); setCreating(false); }}>编辑</button>
<button className="btn btn-ghost btn-sm text-bad" onClick={() => setConfirmDel(ds)}
title="删除数据源及其全部建模">
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
</div>
{job?.dsId === ds.id && job.item && (
<div className="mt-2.5">
<Progress value={job.item.progress} />
<p className="mt-1 text-[11.5px] text-muted">{job.item.message || "处理中…"}</p>
</div>
)}
</div>
))}
</div>
)}
</Card>
<DataSourceForm
open={!!editing} creating={creating} initial={editing}
onClose={() => setEditing(null)}
onSaved={() => { setEditing(null); load(); onChanged(); }} />
<Confirm
open={!!confirmDel} danger title="删除数据源?"
body={`将同时删除「${confirmDel?.name ?? ""}」下的全部建模、关系与指标定义。沉淀的问答对也会失去关联。此操作不可撤销。`}
confirmText="删除" onConfirm={() => confirmDel && remove(confirmDel)}
onClose={() => setConfirmDel(null)} />
</div>
);
}
function DataSourceForm({ open, creating, initial, onClose, onSaved }: {
open: boolean; creating: boolean; initial: DataSource | null;
onClose: () => void; onSaved: () => void;
}) {
const [form, setForm] = useState({ ...BLANK });
const [password, setPassword] = useState("");
const [saving, setSaving] = useState(false);
const [err, setErr] = useState("");
useEffect(() => {
if (!initial) return;
setForm({
name: initial.name ?? "", ds_type: initial.ds_type ?? "mysql", host: initial.host ?? "",
port: initial.port ?? 3306, db_name: initial.db_name ?? "",
username: initial.username ?? "", password: "",
});
setPassword("");
setErr("");
}, [initial]);
const set = (k: string, v: string | number) => setForm((f) => ({ ...f, [k]: v }));
const save = async () => {
setSaving(true);
setErr("");
try {
if (creating) {
await api.createDatasource({ ...form, password });
} else if (initial) {
const body: Record<string, unknown> = { ...form };
delete body.ds_type;
// 留空 = 不改口令。前端不回显明文,所以必须能表达"没动过"
if (password) body.password = password;
else delete body.password;
await api.updateDatasource(initial.id, body);
}
toast("ok", creating ? "数据源已创建" : "数据源已更新");
onSaved();
} catch (e) {
setErr(e instanceof ApiError ? e.message : e instanceof Error ? e.message : String(e));
} finally { setSaving(false); }
};
const ok = form.name.trim() && form.host.trim() && form.db_name.trim() && form.username.trim();
return (
<Modal
open={open} onClose={onClose} width="max-w-xl"
title={creating ? "新建数据源" : "编辑数据源"}
desc="连上业务库之后,还要做一次内省才能开始提问。"
footer={
<>
{err && <p className="mr-auto min-w-0 flex-1 text-[12.5px] text-bad">{err}</p>}
<button className="btn btn-sm" onClick={onClose}>取消</button>
<button className="btn btn-primary btn-sm" disabled={!ok || saving} onClick={save}>
{saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
保存
</button>
</>
}>
<div className="space-y-4">
<Field label="名称" required
hint="给人看的名字,问答页的数据源下拉里显示的就是它。">
<input className="input" value={form.name} placeholder="如:门店运营库(只读)"
onChange={(e) => set("name", e.target.value)} />
</Field>
<div className="space-y-3 rounded-lg border border-line bg-elevated/50 p-3">
<p className="text-[12px] font-medium text-muted">连接信息</p>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
<Field label="主机" required>
<input className="input" value={form.host} placeholder="192.168.x.x"
onChange={(e) => set("host", e.target.value)} />
</Field>
<Field label="端口" required>
<input className="input" type="number" value={form.port}
onChange={(e) => set("port", Number(e.target.value) || 3306)} />
</Field>
</div>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
<Field label="数据库" required>
<input className="input" value={form.db_name} placeholder="库名"
onChange={(e) => set("db_name", e.target.value)} />
</Field>
<Field label="用户名" required>
<input className="input" value={form.username} autoComplete="off"
onChange={(e) => set("username", e.target.value)} />
</Field>
</div>
<Field
label={<>口令{!creating && <span className="ml-1 font-normal">(留空表示不修改)</span>}</>}
required={creating}
hint="加密后存库,任何接口都不会把它回显出来。强烈建议使用只读账号。">
<input className="input" type="password" value={password} autoComplete="new-password"
placeholder={creating ? "" : "••••••••"}
onChange={(e) => setPassword(e.target.value)} />
</Field>
</div>
<p className="text-[11.5px] leading-relaxed text-muted">
目前只支持 MySQL。保存后回到列表点「测试」确认连得通,再点「内省」抓表结构。
</p>
</div>
</Modal>
);
}