import type { KyInstance } from "ky"; import { AuthenticationError } from "../../../../core/errors.js"; import * as api from "../api.js"; import type { WatchWorkflowOptions, WatchedJobResult, WorkflowWatchReport, WorkflowWatchEvent } from "./types.js"; import { normalizeJobStatus, isJobTerminal } from "./helpers.js"; import { watchSingleJob } from "./single-job.js"; /** * 监听工作流流水线:持续捕获新派发的 Job,并实时输出其节点执行动态 */ export async function watchWorkflowPipeline( client: KyInstance, pipelineId: string, options: WatchWorkflowOptions = {} ): Promise { const intervalMs = Math.max(options.intervalMs ?? 2000, 500); const timeoutMs = options.timeoutMs ?? (options.once || options.jobId ? 60000 : Infinity); const maxJobs = options.jobId ? 1 : (options.maxJobs ?? (options.follow ? Infinity : 1)); const startTime = Date.now(); const watchedJobs: WatchedJobResult[] = []; const seenJobIds = new Set(); const emit = async (event: WorkflowWatchEvent) => { if (options.failedOnly) { if ( event.type !== "task_failed" && !(event.type === "task_skipped" && event.error) && event.type !== "job_completed" && event.type !== "timeout" && event.type !== "cancelled" ) { return; } } if (options.onEvent) { await options.onEvent(event); } }; // 1. 如果用户显式指定了 --job= if (options.jobId) { const jobResult = await watchSingleJob(client, options.jobId, { ...options, onEvent: emit, }); watchedJobs.push(jobResult); return { pipelineId, totalJobsWatched: 1, jobs: watchedJobs, timedOut: Boolean(jobResult.timedOut), cancelled: jobResult.cancelled, hasFailures: jobResult.hasError || jobResult.status === "FAILED", }; } // 2. 发出监听开始事件 let pipelineLabel = ""; try { const detail = await api.getWorkflowDetail(client, pipelineId); pipelineLabel = detail.label || ""; } catch { // 忽略标签读取失败 } await emit({ type: "pipeline_watch_start", pipelineId, pipelineLabel, timestamp: Date.now(), }); // 如果是一次性快照检视 (--once) if (options.once) { let targetJobId: string | undefined; // 先查是否有正在运行的任务 try { const running = await api.listRunningJobs(client, pipelineId, "DEBUG"); if (running.length > 0) targetJobId = running[0].id; } catch (error) { if (error instanceof AuthenticationError) throw error; // 忽略 } if (!targetJobId) { try { const logs = await api.listWorkflowLogs(client, pipelineId, { pageSize: 1 }); if (logs.jobList && logs.jobList.length > 0) { const first = logs.jobList[0]; targetJobId = first.jobId || first.id; } } catch { // 忽略 } } if (!targetJobId) { return { pipelineId, totalJobsWatched: 0, jobs: [], timedOut: false, hasFailures: false, }; } const singleRes = await watchSingleJob(client, targetJobId, { ...options, once: true, onEvent: emit, }); return { pipelineId, totalJobsWatched: 1, jobs: [singleRes], timedOut: Boolean(singleRes.timedOut), cancelled: singleRes.cancelled, hasFailures: singleRes.hasError || singleRes.status === "FAILED", }; } // 3. 持续监听循环 let timedOut = false; // 记录初次启动时的最新已知 JobId,避免将老历史任务当作新触发任务(除非有处于 RUNNING 状态的任务) try { const logs = await api.listWorkflowLogs(client, pipelineId, { pageSize: 5 }); for (const j of logs.jobList || []) { const jid = j.jobId || j.id; const status = normalizeJobStatus(j); // 如果不是运行中,标为已知历史 if (jid && !isJobTerminal(status)) { // 运行中的保留待观察 } else if (jid) { seenJobIds.add(jid); } } } catch { // 忽略 } while (Date.now() - startTime < timeoutMs) { if (options.signal?.aborted) break; let candidateJob: { id: string; status: string; runType?: string } | undefined; // 优先检查 running 接口 try { const runningJobs = await api.listRunningJobs(client, pipelineId, "DEBUG"); const found = runningJobs.find((j) => !seenJobIds.has(j.id)); if (found) { candidateJob = { id: found.id, status: found.status || "RUNNING", runType: "DEBUG" }; } } catch (error) { if (error instanceof AuthenticationError) throw error; // 忽略 } // 其次检查流水线最新 log if (!candidateJob) { try { const logs = await api.listWorkflowLogs(client, pipelineId, { pageSize: 3 }); for (const j of logs.jobList || []) { const jid = j.jobId || j.id; if (jid && !seenJobIds.has(jid)) { candidateJob = { id: jid, status: normalizeJobStatus(j), runType: j.runType }; break; } } } catch { // 忽略 } } if (candidateJob) { seenJobIds.add(candidateJob.id); await emit({ type: "job_detected", pipelineId, jobId: candidateJob.id, status: candidateJob.status, runType: candidateJob.runType, timestamp: Date.now(), }); // 实时跟踪该 Job 执行 const jobResult = await watchSingleJob(client, candidateJob.id, { ...options, timeoutMs: Math.max(1, timeoutMs - (Date.now() - startTime)), onEvent: emit, }); watchedJobs.push(jobResult); if (jobResult.timedOut) { timedOut = true; break; } if (jobResult.cancelled) break; if (watchedJobs.length >= maxJobs) { break; } } const elapsed = Date.now() - startTime; const remaining = timeoutMs - elapsed; if (remaining <= 0) { timedOut = true; break; } await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, remaining))); } const cancelled = options.signal?.aborted === true; if (!cancelled && Date.now() - startTime >= timeoutMs && watchedJobs.length < maxJobs) { timedOut = true; if (!watchedJobs.at(-1)?.timedOut) await emit({ type: "timeout", pipelineId, timestamp: Date.now() }); } if (cancelled && !watchedJobs.at(-1)?.cancelled) await emit({ type: "cancelled", pipelineId, timestamp: Date.now() }); const hasFailures = watchedJobs.some((j) => j.hasError || j.status === "FAILED"); return { pipelineId, totalJobsWatched: watchedJobs.length, jobs: watchedJobs, timedOut, cancelled, hasFailures, }; }