Files
seal-use/src/domains/seal/outbound-push.ts
T

220 lines
8.5 KiB
TypeScript

import type { KyInstance } from "ky";
import { confirmationRequired, safetyBlocked, validationError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import * as api from "./api.js";
import type { ApprovalIntegration, ApprovalRun, ApprovalStylePreferences } from "./types.js";
/**
* Shared primitives for pushing a test/replay message into Seal's
* `/api/hosecloud/outbound` gateway. Two callers need them and they must stay
* in lockstep because they build the exact same wire payload:
* - `capabilities/deploy.ts` → `sealDeployHosecloudTestOutbound` (single tenant)
* - `hose-outbound-replay.ts` → `webhook replay --channel hose-outbound` (cross tenant)
*
* Anything that describes the outbound contract (payload shape, blocking nodeId,
* integration selection, the assisted-only gate) lives here so a change to the
* protocol can't drift into one path and not the other.
*/
/**
* Chinese mock nodeId: Hose rejects the callback with HTTP 412 for this node,
* which is what keeps a pushed message from advancing a real approval flow.
*/
export const BLOCKING_NODE_ID = "FLOW:测试模拟节点_禁止流转";
/** Long enough for the worker queue to consume the push before we look for the run. */
const OUTBOUND_VERIFY_WAIT_MS = 2_500;
export interface OutboundPayload {
flowId: string;
nodeId: string;
messageId: string;
rejectionNum: number;
corporationId: string;
}
export function listHoseIntegrations(
preferences: Pick<ApprovalStylePreferences, "integrations">
): ApprovalIntegration[] {
return (preferences.integrations ?? []).filter((item) => item.type === "hosecloud");
}
/**
* Pick the hose integration a push should target. An explicit signKey must
* match; without one, an ambiguous list is an error rather than a guess —
* pushing to the wrong outbound channel is not something to default silently.
*/
export function selectHoseIntegration(options: {
integrations: ApprovalIntegration[];
signKey?: string;
corpName: string;
corpId: string;
}): ApprovalIntegration {
const { integrations, corpName, corpId } = options;
if (integrations.length === 0) {
throw validationError(
`企业「${corpName}」未配置任何合思出站发布通道。\n` +
`请先运行:seal-use deploy hosecloud configure --json '{...}' --corp ${corpId}`
);
}
if (options.signKey) {
const found = integrations.find((item) => item.signKey === options.signKey);
if (!found) {
throw validationError(
`未找到 signKey 为「${options.signKey}」的合思配置。可用 signKey: ` +
`${integrations.map((item) => item.signKey).filter(Boolean).join(", ")}`
);
}
return requireSignKey(found, corpName);
}
if (integrations.length > 1) {
const list = integrations
.map((item) => `"${item.outboundName ?? "SealAI 审批"}" (signKey: ${item.signKey})`)
.join(", ");
throw validationError(
`企业「${corpName}」存在多个合思集成 [${list}],请通过 --sign-key 指定目标集成配置。`
);
}
return requireSignKey(integrations[0]!, corpName);
}
function requireSignKey(integration: ApprovalIntegration, corpName: string): ApprovalIntegration {
if (!integration.signKey) {
throw validationError(`企业「${corpName}」的合思出站配置未保存 signKey,请重新执行 configure。`);
}
return integration;
}
/**
* Every push must target an `assisted` integration: any other mode lets the
* result callback write approval actions back into the flow autonomously.
*/
export function assertAssistedIntegration(
integration: Pick<ApprovalIntegration, "signKey" | "outboundName" | "mode">,
options: { corpName: string; corpId: string }
): void {
const mode = integration.mode ?? "assisted";
if (mode === "assisted") {
return;
}
throw safetyBlocked(
`安全阻断:企业「${options.corpName}」的合思配置「${integration.outboundName ?? integration.signKey}」` +
`当前为「${mode}」模式,非 assisted(辅助审核)模式。\n` +
`为防止自动向合思回写审批动作影响审批流程,严禁在非 assisted 模式下推送出站报文。`,
`seal-use deploy hosecloud configure --json '{"signKey":"${integration.signKey}","mode":"assisted"}' --corp ${options.corpId}`
);
}
export function buildOutboundWebhookUrl(corp: CorpConfig, signKey: string): string {
const sealUrl = (corp.seal.url ?? `https://${corp.id.toLowerCase()}.sealai.cc`).replace(/\/+$/, "");
return `${sealUrl}/api/hosecloud/outbound?config_id=${encodeURIComponent(signKey)}`;
}
export function buildOutboundPayload(options: {
flowId: string;
messageId: string;
nodeId?: string;
rejectionNum?: number;
corporationId: string;
}): OutboundPayload {
return {
flowId: options.flowId,
nodeId: options.nodeId?.trim() || BLOCKING_NODE_ID,
messageId: options.messageId,
rejectionNum: options.rejectionNum ?? 0,
corporationId: options.corporationId
};
}
/**
* Hose document SNs double as flowIds only when they carry the ID01 prefix;
* any other SN needs a lookup to resolve the flow instance.
*/
export function flowIdFromDocumentSn(sn: string | undefined): string | undefined {
return sn?.startsWith("ID01") ? sn : undefined;
}
export function resolveCorporationId(candidates: Array<string | undefined>): string {
const found = candidates.map((value) => value?.trim()).find((value) => value);
if (!found) {
throw validationError(
"缺少 corporationId,且当前合思集成未保存有效 corporationId,请通过 --corporation-id 参数显式提供。"
);
}
return found;
}
/**
* Push the payload, then poll approval runs to report whether the queue
* consumed it. The poll is advisory: a miss only downgrades the message to
* "queued", it never fails the push that already succeeded.
* Only a recordId returned by this push can associate a run with this message;
* finding the same document in a list also finds historical or concurrent runs.
*/
export async function pushOutboundAndVerify(options: {
client: KyInstance;
signKey: string;
payload: OutboundPayload;
flowId: string;
sn?: string;
confirm?: boolean;
corpName: string;
corpId: string;
/** Channel-specific success lines logged right after the push lands. */
pushedMessages?: string[];
/** Queue-drain wait before polling; injectable so tests don't sleep. */
verifyWaitMs?: number;
}): Promise<{ response: Awaited<ReturnType<typeof api.postHosecloudOutbound>>; createdRecord?: ApprovalRun }> {
const { client, signKey, payload, flowId, sn, corpName, corpId } = options;
if (options.confirm !== true) {
throw confirmationRequired(
"Refusing to push an outbound test/replay message without --yes or --confirm. Use --dry-run to preview first.",
"seal-use help deploy hosecloud test-outbound"
);
}
const response = await api.postHosecloudOutbound(client, signKey, payload);
if (response.success === false) {
throw new Error(`合思出站推送失败:${response.message ?? "上游拒绝请求"}`);
}
for (const line of options.pushedMessages ?? []) {
console.error(line);
}
// `sn` is optional: callers that only know the flowId leave it undefined, and
// an undefined needle must never match a record whose SN is absent — that
// would report an unrelated run as the one this push just created.
const snNeedle = sn?.trim() || undefined;
let createdRecord: ApprovalRun | undefined;
const recordId = typeof response.recordId === "string" ? response.recordId.trim() : undefined;
if (recordId) {
await new Promise((resolve) => setTimeout(resolve, options.verifyWaitMs ?? OUTBOUND_VERIFY_WAIT_MS));
try {
const record = await api.getApprovalRun(client, recordId);
const sameDocument = record.sourceDocumentId === flowId ||
(!record.sourceDocumentId && (record.sourceDocumentSN === flowId ||
(snNeedle !== undefined && record.sourceDocumentSN === snNeedle)));
if (record.id === recordId && sameDocument) {
createdRecord = record;
}
} catch {
// Non-blocking: the run may not exist yet even when the push succeeded.
}
}
if (createdRecord) {
console.error(`✓ 已确认本次推送关联【${corpName}】审核记录: ${createdRecord.id} (任务模式: ${createdRecord.taskMode})`);
console.error(`👉 查看审核详情: seal-use approval-runs get ${createdRecord.id} --corp ${corpId}`);
} else {
console.error(`ℹ️ 推送已接受,异步消费尚未确认,可稍后执行: seal-use approval-runs list --corp ${corpId}`);
}
return { response, createdRecord };
}