PipelinePage.tsx 11.4 KB
import { Play, Plus, RefreshCw, Search, Trash2, Workflow } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { Badge, Card, CardHeader, Empty, Segmented, Spinner, Stat } from "@/components/ui";
import { confirmDialog } from "@/lib/dialog";
import { go } from "@/lib/nav";
import { errText, fmtTime, onto, type ConceptBrief, type Me, type PipelineRec } from "@/lib/onto";
import { toast } from "@/store/useAppStore";

const SCHED: Record<string, string> = { manual: "手动", hourly: "每小时", daily: "每天" };
const TONE: Record<string, string> = { ok: "bg-ok/10 text-ok", failed: "bg-bad/10 text-bad", running: "bg-brand2/10 text-brand2", idle: "bg-ink/5 text-muted" };

/**
 * 数据管道:把每个对象类型的「骨架」(主键、显示名、关系键、维度属性)从业务库同步进来,
 * 并按关系物化出关系边。业务明细仍然实时查业务库 —— 骨架只用于对象搜索、多跳遍历与影响分析。
 */
export function PipelinePage({ me }: { me: Me | null }) {
  const canEdit = !!me?.permissions.includes("build");
  const [tab, setTab] = useState<"pipes" | "dataset">("pipes");
  const [data, setData] = useState<{ items: PipelineRec[]; status: { objects: number; edges: number; synced_at: string | null } } | null>(null);
  const [objs, setObjs] = useState<ConceptBrief[]>([]);
  const [busy, setBusy] = useState("");
  const load = useCallback(() => {
    void onto.pipelines().then(setData).catch((e) => toast("error", errText(e)));
    void onto.concepts({ kind: "object_type" }).then(setObjs).catch(() => undefined);
  }, []);
  useEffect(load, [load]);
  // 有管道在同步时(后台全部同步)轮询状态
  const running = (data?.items || []).some((p) => p.status === "running") || busy === "all";
  // 点了「全部同步」后后台任务可能还没开始,状态还不是 running:先按时间轮询一阵,别让页面停在旧状态
  const [syncSince, setSyncSince] = useState(0);
  useEffect(() => {
    if (!syncSince) return;
    const t = window.setInterval(() => {
      void onto.pipelines().then((d) => {
        setData(d);
        const done = d.items.every((p) => p.status !== "running" && p.last_run_at && Date.parse(p.last_run_at) >= syncSince - 2000);
        if (done || Date.now() - syncSince > 120000) setSyncSince(0);
      }).catch(() => setSyncSince(0));
    }, 2000);
    return () => window.clearInterval(t);
  }, [syncSince]);
  useEffect(() => {
    if (!running) return;
    const t = window.setInterval(load, 3000);
    return () => window.clearInterval(t);
  }, [running, load]);
  const has = new Set((data?.items || []).map((p) => p.object_type_id));
  const candidates = objs.filter((o) => o.mapped && o.published && !has.has(o.id));
  const act = async (key: string, fn: () => Promise<unknown>, ok: string) => {
    setBusy(key);
    try { await fn(); toast("ok", ok); load(); } catch (e) { toast("error", errText(e)); } finally { setBusy(""); }
  };

  return (
    <div className="mx-auto max-w-6xl space-y-4">
      <Card className="grid gap-4 p-4 sm:grid-cols-4">
        <Stat label="数据管道" value={data?.items.length ?? "-"} hint={`${(data?.items || []).filter((p) => p.status === "ok").length} 条正常`} />
        <Stat label="已同步对象" value={data?.status.objects ?? "-"} hint="只同步主键 / 名称 / 关系键,明细仍实时查" />
        <Stat label="关系边" value={data?.status.edges ?? "-"} hint="影响分析沿这些边遍历" />
        <Stat label="数据截至" value={<span className="text-title">{fmtTime(data?.status.synced_at)}</span>} />
      </Card>
      <div className="flex flex-wrap items-center gap-2">
        <Segmented value={tab} onChange={setTab} options={[{ key: "pipes", label: "数据管道" }, { key: "dataset", label: "本体数据集" }]} />
        <span className="flex-1" />
        {canEdit && tab === "pipes" && <>
          <button className="btn btn-sm" disabled={!!busy || !candidates.length} title="给所有已映射、已发布、还没有管道的对象类型建管道"
                  onClick={() => void act("ensure", async () => { const r = await onto.ensurePipelines(); return r; }, "已补齐管道")}>
            <Plus className="h-3.5 w-3.5" />为已映射对象补齐 {candidates.length}</button>
          <button className="btn btn-primary btn-sm" disabled={!!busy || running || !!syncSince || !data?.items.length}
                  onClick={async () => {
                    try { await onto.runAllPipelines(); setSyncSince(Date.now()); toast("info", "已开始后台同步", "状态会实时刷新,可以离开这个页面"); load(); }
                    catch (e) { toast("error", errText(e)); }
                  }}>
            {running || syncSince ? <Spinner className="h-3.5 w-3.5" /> : <RefreshCw className="h-3.5 w-3.5" />}全部同步</button>
        </>}
      </div>

      {tab === "dataset" ? <Dataset objs={objs.filter((o) => has.has(o.id))} /> : (
        <Card>
          <CardHeader title="管道" desc="同步顺序无所谓:每跑一条都会重建和它相关的关系边(两端骨架都在才有边)" />
          {!data ? <div className="p-4"><Spinner /></div> : !data.items.length ? (
            <Empty icon={<Workflow className="h-10 w-10" />} title="还没有数据管道"
                   desc="对象类型映射到数据表并发布后,在这里建管道同步骨架,就能做对象搜索与影响分析。"
                   action={<button className="btn btn-sm" onClick={() => go("b_object")}>去看对象类型</button>} />
          ) : (
            <table className="w-full text-label">
              <thead className="text-label text-muted"><tr className="border-b border-line">
                <th className="px-4 py-2 text-left">对象类型</th><th className="px-2 text-left">调度</th><th className="px-2 text-left">状态</th>
                <th className="px-2 text-right">对象</th><th className="px-2 text-right">关系边</th><th className="px-2 text-left">上次同步</th><th className="px-4" /></tr></thead>
              <tbody>
                {data.items.map((p) => (
                  <tr key={p.id} className="border-b border-line/60">
                    <td className="px-4 py-2 font-medium"><button onClick={() => go("b_object", { id: p.object_type_id })}>{p.object_type}</button></td>
                    <td className="px-2">
                      <select className="input h-7 w-24 py-0 text-label" disabled={!canEdit} value={p.schedule}
                              onChange={(e) => void act(p.id, () => onto.updatePipeline(p.id, { schedule: e.target.value as PipelineRec["schedule"] }), "已更新调度")}>
                        {Object.entries(SCHED).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
                      </select>
                    </td>
                    <td className="px-2"><Badge tone={TONE[p.status]}>{{ ok: "正常", failed: "失败", running: "同步中", idle: "未运行" }[p.status] || p.status}</Badge>
                      {p.last_error && <p className="max-w-[260px] truncate text-caption text-bad" title={p.last_error}>{p.last_error}</p>}</td>
                    <td className="px-2 text-right tabular-nums">{p.last_rows}</td>
                    <td className="px-2 text-right tabular-nums">{p.last_edges}</td>
                    <td className="px-2 text-muted">{fmtTime(p.last_run_at)}{p.last_duration_ms ? ` · ${p.last_duration_ms} ms` : ""}</td>
                    <td className="px-4 text-right">
                      {canEdit && <>
                        <button className="btn btn-sm" disabled={!!busy} onClick={() => void act(p.id, () => onto.runPipeline(p.id), `「${p.object_type}」同步完成`)}>
                          {busy === p.id ? <Spinner className="h-3.5 w-3.5" /> : <Play className="h-3.5 w-3.5" />}同步</button>
                        <button className="btn btn-ghost btn-sm text-bad" onClick={async () => {
                          if (!(await confirmDialog(`删除「${p.object_type}」的管道?`, { desc: "已同步的骨架与相关关系边一并清除;业务库不受影响", danger: true }))) return;
                          void act(p.id, () => onto.deletePipeline(p.id), "已删除");
                        }}><Trash2 className="h-3.5 w-3.5" /></button>
                      </>}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
          {canEdit && candidates.length > 0 && (
            <div className="flex flex-wrap items-center gap-1.5 border-t border-line px-4 py-3 text-label">
              <span className="text-muted">可建管道:</span>
              {candidates.map((o) => (
                <button key={o.id} className="chip" onClick={() => void act(o.id, () => onto.createPipeline(o.id), `已为「${o.name}」建管道`)}>
                  <Plus className="h-3 w-3" />{o.name}</button>
              ))}
            </div>
          )}
        </Card>
      )}
    </div>
  );
}

function Dataset({ objs }: { objs: ConceptBrief[] }) {
  const [type, setType] = useState(objs[0]?.id || "");
  const [q, setQ] = useState("");
  const [data, setData] = useState<Awaited<ReturnType<typeof onto.dataset>> | null>(null);
  useEffect(() => { if (!type && objs[0]) setType(objs[0].id); }, [objs, type]);
  useEffect(() => {
    if (!type) return;
    const t = window.setTimeout(() => void onto.dataset(type, q, 100).then(setData).catch(() => setData(null)), 200);
    return () => window.clearTimeout(t);
  }, [type, q]);
  if (!objs.length) return <Card><Empty title="还没有同步过的对象类型" desc="先建管道并同步。" /></Card>;
  const cols = [...new Set((data?.items || []).flatMap((x) => Object.keys(x.properties || {})))].slice(0, 8);
  return (
    <Card>
      <div className="flex flex-wrap items-center gap-2 border-b border-line px-4 py-3">
        <select className="input h-8 w-48" value={type} onChange={(e) => setType(e.target.value)}>
          {objs.map((o) => <option key={o.id} value={o.id}>{o.name}</option>)}
        </select>
        <div className="relative"><Search className="absolute left-2 top-2 h-3.5 w-3.5 text-muted" />
          <input className="input h-8 w-56 pl-7" placeholder="按显示名 / 主键找" value={q} onChange={(e) => setQ(e.target.value)} /></div>
        <span className="ml-auto text-label text-muted">{data ? `共 ${data.total} 个` : ""}</span>
      </div>
      <div className="max-h-[60vh] overflow-auto">
        <table className="w-full text-label">
          <thead className="sticky top-0 bg-surface text-label text-muted"><tr className="border-b border-line">
            <th className="px-4 py-2 text-left">主键</th><th className="px-2 text-left">显示名</th>
            {cols.map((c) => <th key={c} className="px-2 text-left">{c}</th>)}<th className="px-2 text-left">同步于</th></tr></thead>
          <tbody>
            {(data?.items || []).map((x) => (
              <tr key={x.key} className="cursor-pointer border-b border-line/60 hover:bg-ink/[0.03]" onClick={() => go("objects", { type, key: x.key })}>
                <td className="px-4 py-1.5 font-mono">{x.key}</td><td className="px-2">{x.label}</td>
                {cols.map((c) => <td key={c} className="px-2 text-muted">{String(x.properties?.[c] ?? "")}</td>)}
                <td className="px-2 text-caption text-muted">{fmtTime(x.synced_at)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </Card>
  );
}