Files
seal-use/src/domains/seal/testing/sync.ts
T
gitea 887df2d32f Add cloud enterprise storage mode and credential resolver
Enterprise configs gain a root-level storage field (default local). Cloud configs must not persist any secret and fail closed on load. Route credential reads through resolveCorpCredentials, which returns local fields unchanged and fails with exit code 11 for cloud enterprises until the bridge client lands. Cloud enterprises skip the local token store and delegation renewal.
2026-11-19 17:00:45 +08:00

363 lines
17 KiB
TypeScript

import { randomBytes } from "node:crypto";
import type { KyInstance } from "ky";
import { createSealClient } from "../../../core/http/factory.js";
import { resolveCorpCredentials } from "../../../core/auth/credentials.js";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import type { CorpConfig } from "../../../core/config/types.js";
import * as api from "../api.js";
import { computeNextSyncIteration, formatSyncVersionName, saveRuleMappingSnapshot } from "../rules/mapping.js";
import { savePublishedRuleVersionSnapshot } from "../rules/version-snapshot.js";
export type TestSyncOptions = {
versionName?: string;
dryRun?: boolean;
execute?: boolean;
};
export async function syncTestEnterprise(
prodCorp: CorpConfig,
testCorp: CorpConfig,
options: TestSyncOptions = {}
) {
const prodClient = await createSealClient(prodCorp);
const testClient = await createSealClient(testCorp);
const [
prodPref,
testPref,
prodRules,
testRules,
prodVersions,
testVersions,
prodDocsRes,
testDocsRes
] = await Promise.all([
api.getApprovalStylePreferences(prodClient, prodCorp.seal.endpoints.approvalStylePreferences),
api.getApprovalStylePreferences(testClient, testCorp.seal.endpoints.approvalStylePreferences),
api.listApprovalRules(prodClient),
api.listApprovalRules(testClient),
api.listApprovalRuleVersions(prodClient),
api.listApprovalRuleVersions(testClient),
listAllApprovalDocuments(prodClient),
listAllApprovalDocuments(testClient)
]);
const prodDocs = (prodDocsRes.articles || []).filter((doc) => !doc.isDeleted);
const testDocs = (testDocsRes.articles || []).filter((doc) => !doc.isDeleted);
const testDocsByTitle = new Map(testDocs.map((doc) => [doc.title.trim(), doc]));
const docsToCreate: any[] = [];
const docsToUpdate: any[] = [];
const prodTitles = new Set(prodDocs.map((doc) => doc.title.trim()));
for (const prodDoc of prodDocs) {
const title = prodDoc.title.trim();
const existing = testDocsByTitle.get(title);
if (!existing) {
docsToCreate.push(prodDoc);
continue;
}
const reasons = [
["content", existing.content !== prodDoc.content],
["purpose", (existing.purpose ?? "") !== (prodDoc.purpose ?? "")],
["enabled", existing.enabled !== prodDoc.enabled],
["contentType", existing.contentType !== prodDoc.contentType],
["status", (existing.status ?? "") !== (prodDoc.status ?? "")],
["scenarios", JSON.stringify([...(existing.scenarios ?? [])].sort()) !== JSON.stringify([...(prodDoc.scenarios ?? [])].sort())],
["tags", JSON.stringify([...(existing.tags ?? [])].sort()) !== JSON.stringify([...(prodDoc.tags ?? [])].sort())]
].filter(([, changed]) => changed).map(([reason]) => reason as string);
if (reasons.length > 0) docsToUpdate.push({ testId: existing.id, prodDoc, reasons });
}
const docsToDelete = testDocs.filter((doc) => !prodTitles.has(doc.title.trim()));
const sortedProdVersions = [...prodVersions].sort((a, b) => b.versionNumber - a.versionNumber);
const latestProd = sortedProdVersions[0];
const prodVersionNumber = latestProd?.versionNumber;
const sortedTestVersions = [...testVersions].sort((a, b) => b.versionNumber - a.versionNumber);
const targetTestExpectedVersionNumber = (sortedTestVersions[0]?.versionNumber ?? 0) + 1;
const nextIteration = computeNextSyncIteration(prodCorp.name, prodVersionNumber, testVersions);
const versionName = options.versionName ?? formatSyncVersionName(
prodCorp.name,
prodVersionNumber,
nextIteration,
targetTestExpectedVersionNumber
);
const updatedTestPref = {
...testPref,
tone: prodPref.tone,
language: prodPref.language,
detailLevel: prodPref.detailLevel,
outputFormat: prodPref.outputFormat,
examples: prodPref.examples ?? [],
prohibitedPhrases: prodPref.prohibitedPhrases ?? [],
customInstructions: prodPref.customInstructions,
decisionPreferences: prodPref.decisionPreferences,
thinkingDepthPreference: prodPref.thinkingDepthPreference
};
if (options.dryRun || options.execute === false) {
const testSignatureSet = new Set(
testRules.rules.map((r) => JSON.stringify([r.description ?? "", r.scope ?? "", r.strictness ?? ""]))
);
const allSyncItems = prodRules.rules.map((rule, index) => {
const code = rule.code ?? index;
const sig = JSON.stringify([rule.description ?? "", rule.scope ?? "", rule.strictness ?? ""]);
const existingAtIndex = testRules.rules[index];
const isUnchanged =
(existingAtIndex &&
existingAtIndex.description === rule.description &&
existingAtIndex.scope === rule.scope &&
existingAtIndex.strictness === rule.strictness) ||
testSignatureSet.has(sig);
return {
index,
sourceRuleId: rule.id,
sourceRuleCode: code,
expectedTargetCode: `rule-${code}`,
description: rule.description,
scope: rule.scope,
strictness: rule.strictness,
unchanged: isUnchanged
};
});
const changedRules = allSyncItems
.filter((item) => !item.unchanged)
.map(({ unchanged: _unchanged, ...rest }) => rest);
const unchangedCount = allSyncItems.length - changedRules.length;
return {
dryRun: true as const,
source: {
id: prodCorp.id,
name: prodCorp.name,
environment: prodCorp.environment,
latestPublishedVersion: latestProd ? { versionNumber: latestProd.versionNumber, versionName: latestProd.versionName } : null,
documentsCount: prodDocs.length
},
target: { id: testCorp.id, name: testCorp.name, environment: testCorp.environment },
versionMappingPlan: {
sourceProdVersionNumber: prodVersionNumber ?? null,
sourceProdVersionName: latestProd?.versionName ?? null,
targetTestExpectedVersionNumber,
targetTestPublishVersionName: versionName,
iteration: nextIteration
},
preferencesDiff: {
decisionPreferences: { before: testPref.decisionPreferences, after: prodPref.decisionPreferences },
thinkingDepthPreference: { before: testPref.thinkingDepthPreference, after: prodPref.thinkingDepthPreference }
},
rulesPlan: {
sourceDraftRuleCount: prodRules.rules.length,
targetExistingDraftRuleCount: testRules.rules.length,
toDeleteCount: testRules.rules.length,
toCreateCount: prodRules.rules.length,
unchangedCount,
changedCount: changedRules.length,
rulesToSync: changedRules
},
documentsPlan: {
sourceDocumentCount: prodDocs.length,
targetExistingDocumentCount: testDocs.length,
toCreateCount: docsToCreate.length,
toCreate: docsToCreate.map((doc) => ({ title: doc.title, purpose: doc.purpose, contentType: doc.contentType, scenarios: doc.scenarios })),
toUpdateCount: docsToUpdate.length,
toUpdate: docsToUpdate.map((item) => ({ targetDocumentId: item.testId, title: item.prodDoc.title, reasons: item.reasons })),
toDeleteCount: docsToDelete.length,
toDelete: docsToDelete.map((doc) => ({ targetDocumentId: doc.id, title: doc.title }))
},
publishingPlan: { targetCorpId: testCorp.id, publishVersionName: versionName, publishTarget: "test" },
hosecloudSyncPlan: buildHosecloudSyncPlan(prodCorp, prodPref),
productionGuarantees: { prodRulesStayDraft: true, prodVersionPublished: false }
};
}
await api.updateApprovalStylePreferences(testClient, updatedTestPref, testCorp.seal.endpoints.approvalStylePreferences);
const deletedDocs: Array<{ id: string; title: string }> = [];
for (const doc of docsToDelete) {
await api.deleteApprovalDocument(testClient, doc.id);
deletedDocs.push({ id: doc.id, title: doc.title });
}
const updatedDocs: Array<{ id: string; title: string; reasons: string[] }> = [];
for (const item of docsToUpdate) {
await api.updateApprovalDocument(testClient, item.testId, {
title: item.prodDoc.title,
purpose: item.prodDoc.purpose,
content: item.prodDoc.content,
contentType: item.prodDoc.contentType,
status: item.prodDoc.status,
enabled: item.prodDoc.enabled,
scenarios: item.prodDoc.scenarios && item.prodDoc.scenarios.length > 0 ? item.prodDoc.scenarios : ["audit"],
tags: item.prodDoc.tags
});
updatedDocs.push({ id: item.testId, title: item.prodDoc.title, reasons: item.reasons });
}
const createdDocs: Array<{ id: string; title: string }> = [];
for (const doc of docsToCreate) {
const created = await api.createApprovalDocument(testClient, {
title: doc.title,
purpose: doc.purpose,
content: doc.content,
contentType: doc.contentType,
status: doc.status,
enabled: doc.enabled,
scenarios: doc.scenarios && doc.scenarios.length > 0 ? doc.scenarios : ["audit"],
tags: doc.tags
});
createdDocs.push({ id: created.id, title: created.title });
}
for (const rule of testRules.rules) await api.deleteApprovalRule(testClient, rule.id);
// Reset only after confirming the draft is empty, before allocating new codes.
const recodeResult = await api.recodeApprovalRules(testClient) as { ok: boolean; status: number };
if (!recodeResult.ok) throw new Error(`Failed to recode test approval rules: HTTP ${recodeResult.status}`);
const createdRules: any[] = [];
for (const rule of prodRules.rules) {
createdRules.push(await api.createApprovalRule(testClient, {
description: rule.description,
scope: rule.scope,
strictness: rule.strictness
}));
}
const hosecloudSync = await syncHosecloudIntegrationsToTest(prodCorp, testCorp, prodClient, testClient);
const published = await api.publishApprovalRuleVersion(testClient, versionName);
try { savePublishedRuleVersionSnapshot(testCorp.id, published.version, createdRules); } catch {}
const publishedRules = published.version.rules ?? [];
const ruleMapping = prodRules.rules.map((prodRule, index) => ({
index,
sourceRuleId: prodRule.id,
sourceRuleCode: prodRule.code ?? index,
targetRuleId: createdRules[index]?.id ?? "",
targetRuleCode: publishedRules[index]?.code ?? `rule-${prodRule.code ?? index}`,
description: prodRule.description,
scope: prodRule.scope,
strictness: prodRule.strictness
}));
const versionMapping = {
sourceProdVersionNumber: prodVersionNumber ?? null,
sourceProdVersionName: latestProd?.versionName ?? null,
targetTestVersionNumber: published.version.versionNumber,
targetTestVersionName: published.version.versionName ?? null
};
let mappingSavedTo: string | undefined;
const syncedAt = formatBeijingIso();
try {
mappingSavedTo = saveRuleMappingSnapshot({
syncedAt,
source: { id: prodCorp.id, name: prodCorp.name, latestPublishedVersionNumber: prodVersionNumber ?? null, latestPublishedVersionName: latestProd?.versionName ?? null },
target: { id: testCorp.id, name: testCorp.name, publishedVersionNumber: published.version.versionNumber, publishedVersionName: published.version.versionName, rulesCount: published.rulesCount },
versionMapping,
ruleMapping
});
} catch {}
return {
success: true as const,
syncedAt,
source: {
id: prodCorp.id,
name: prodCorp.name,
environment: prodCorp.environment,
latestPublishedVersion: latestProd ? { versionNumber: latestProd.versionNumber, versionName: latestProd.versionName } : null,
draftRulesCount: prodRules.rules.length,
documentsCount: prodDocs.length
},
target: {
id: testCorp.id,
name: testCorp.name,
environment: testCorp.environment,
deletedDraftRulesCount: testRules.rules.length,
createdDraftRulesCount: createdRules.length,
publishedVersion: { id: published.version.id, versionNumber: published.version.versionNumber, versionName: published.version.versionName, rulesCount: published.rulesCount }
},
documents: { sourceCount: prodDocs.length, targetExistingCount: testDocs.length, createdCount: createdDocs.length, created: createdDocs, updatedCount: updatedDocs.length, updated: updatedDocs, deletedCount: deletedDocs.length, deleted: deletedDocs },
versionMapping,
ruleMapping,
...(mappingSavedTo ? { mappingSavedTo } : {}),
hosecloudSync,
productionGuarantees: { prodRulesStayDraft: true, prodVersionPublished: false }
};
}
async function listAllApprovalDocuments(client: KyInstance) {
const pageSize = 100;
const documents: Awaited<ReturnType<typeof api.listApprovalDocuments>>["articles"] = [];
let offset = 0;
while (true) {
const page = await api.listApprovalDocuments(client, { offset, limit: pageSize });
documents.push(...page.articles);
offset += page.articles.length;
if (page.articles.length === 0 || page.articles.length < pageSize) break;
if (page.total !== undefined && offset >= page.total) break;
}
return { articles: documents, total: documents.length };
}
export function buildTestHosecloudOutboundName(corpName: string): string {
const suffix = "(Seal测)";
return [...corpName].slice(0, 13 - suffix.length).join("") + suffix;
}
function buildHosecloudSyncPlan(prodCorp: CorpConfig, prodPref: any) {
if (prodCorp.source.type !== "hose") return { sourceType: prodCorp.source.type, skipped: true, reason: "prod source is not hose; no hosecloud credentials available" };
const seen = new Set<string>();
const integrations = (prodPref.integrations ?? []).filter((item: any) => item.type === "hosecloud").filter((item: any) => {
const corpId = item.corporationId ?? prodCorp.id;
if (seen.has(corpId)) return false;
seen.add(corpId);
return true;
});
return {
sourceType: "hose",
outboundName: buildTestHosecloudOutboundName(prodCorp.name),
targetMode: "assisted",
integrationsCount: integrations.length,
integrations: integrations.map((item: any) => ({ corporationId: item.corporationId, apiOrigin: item.apiOrigin, customApiUrl: item.customApiUrl }))
};
}
interface HosecloudSyncResult {
skipped: boolean;
reason?: string;
synced?: Array<{ signKey: string; outboundName: string; corporationId: string; action: "created" | "updated" }>;
}
async function syncHosecloudIntegrationsToTest(prodCorp: CorpConfig, testCorp: CorpConfig, prodClient: KyInstance, testClient: KyInstance): Promise<HosecloudSyncResult> {
if (prodCorp.source.type !== "hose") return { skipped: true, reason: "prod source is not hose; no hosecloud credentials available" };
const credentials = await resolveCorpCredentials(prodCorp);
const appKey = credentials.appKey?.trim();
const appSecurity = credentials.appSecurity?.trim();
if (!appKey || !appSecurity) return { skipped: true, reason: "prod hose source missing appKey/appSecurity" };
const [prodPref, testPref] = await Promise.all([
api.getApprovalStylePreferences(prodClient, prodCorp.seal.endpoints.approvalStylePreferences),
api.getApprovalStylePreferences(testClient, testCorp.seal.endpoints.approvalStylePreferences)
]);
const prodIntegrations: any[] = (prodPref.integrations ?? []).filter((item: any) => item.type === "hosecloud");
if (prodIntegrations.length === 0) return { skipped: true, reason: "prod Seal enterprise has no hosecloud integrations configured" };
const seenCorpIds = new Set<string>();
const distinct = prodIntegrations.filter((item) => {
const corpId = item.corporationId ?? prodCorp.id;
if (seenCorpIds.has(corpId)) return false;
seenCorpIds.add(corpId);
return true;
}).map((item) => ({ ...item, corporationId: item.corporationId ?? prodCorp.id }));
const testIntegrations: any[] = testPref.integrations ?? [];
const testByCorpId = new Map<string, any>(testIntegrations.filter((item) => item.type === "hosecloud").map((item) => [item.corporationId, item]));
const outboundName = buildTestHosecloudOutboundName(prodCorp.name);
const synced: HosecloudSyncResult["synced"] = [];
const nextIntegrations = distinct.map((prodInt) => {
const existing = testByCorpId.get(prodInt.corporationId);
const signKey = existing?.signKey ?? randomBytes(6).toString("hex");
synced!.push({ signKey, outboundName, corporationId: prodInt.corporationId, action: existing ? "updated" : "created" });
return {
type: "hosecloud",
signKey,
outboundName,
mode: "assisted",
apiKey: appKey,
apiSecret: appSecurity,
apiOrigin: prodInt.apiOrigin,
...(prodInt.customApiUrl ? { customApiUrl: prodInt.customApiUrl } : {}),
corporationId: prodInt.corporationId
};
});
const otherIntegrations = testIntegrations.filter((item) => item.type !== "hosecloud");
await api.updateApprovalStylePreferences(testClient, { ...testPref, integrations: [...otherIntegrations, ...nextIntegrations] }, testCorp.seal.endpoints.approvalStylePreferences);
return { skipped: false, synced };
}