Przeglądaj źródła

feat(平台): 增加 FTS 安全预检并修正定时器时区

apple 1 miesiąc temu
rodzic
commit
b7768a298a

+ 157 - 0
src/biz/pxm/FtsRebuildServ.java

@@ -0,0 +1,157 @@
+package biz.pxm;
+
+import base.po.PxmPo;
+import base.po.PxmhjPo;
+import biz.pwj.PwjlbE;
+import core.PmsU;
+import core.PrjApp;
+import core.cfg.CfgLoader;
+import core.fts.rebuild.FtsRebuildPlanB;
+import core.fts.rebuild.FtsRebuildPlanner;
+import core.fts.rebuild.FtsRebuildSelectionB;
+import core.prj.PrjXs;
+import core.rls.RlsU;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpSession;
+import ss.WebC;
+import ss.cmn.str.StrUuid;
+import ss.db.Db;
+import ss.ddp.DdpC;
+import ss.ddp.DdpU;
+import ss.fts.Fts;
+import ss.obj.ObjB;
+import ss.serv.Serv;
+import ss.serv.ServC;
+
+import java.util.Comparator;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class FtsRebuildServ extends Serv {
+
+	private static final String SELECTION_SESSION_PREFIX = "FTS-REBUILD-SELECTION-";
+	private static final String PLAN_SESSION_PREFIX = "FTS-REBUILD-PLAN-";
+
+	@SuppressWarnings("unused")
+	public String searchFtsRebuildCandidates() throws Exception {
+		HttpServletRequest request = super.req;
+		long pxmid = readLongParameter(request, "pxmid");
+		long pxmhjid = readLongParameter(request, "pxmhjid");
+		ProjectContext context = loadProjectContext(pxmid, pxmhjid, super.fetchDba());
+		List<ObjB> candidates = context.cfg.objMap.values().stream()
+				.filter(obj -> obj.hasFts && obj.isRoot)
+				.sorted(Comparator.comparing(obj -> obj.name))
+				.toList();
+		Set<String> allowedObjectNames = candidates.stream()
+				.map(obj -> obj.name)
+				.collect(Collectors.toSet());
+
+		String requestId = StrUuid.makeUuid();
+		request.getSession().setAttribute(SELECTION_SESSION_PREFIX + requestId,
+				new FtsRebuildSelectionB(pxmid, pxmhjid, allowedObjectNames));
+		request.setAttribute("ftsIdxList", candidates);
+		request.setAttribute("pxmid", pxmid);
+		request.setAttribute("pxmhjid", pxmhjid);
+		request.setAttribute("gxid", requestId);
+		return WebC.FWD_def;
+	}
+
+	@SuppressWarnings("unused")
+	public String dryRunFtsRebuild() throws Exception {
+		HttpServletRequest request = super.req;
+		long pxmid = readLongParameter(request, "pxmid");
+		long pxmhjid = readLongParameter(request, "pxmhjid");
+		String requestId = request.getParameter("gxid");
+		request.setAttribute("pxmid", pxmid);
+		request.setAttribute("pxmhjid", pxmhjid);
+		request.setAttribute("gxid", requestId);
+
+		Set<String> selectedObjectNames;
+		try {
+			selectedObjectNames = DdpU.rdDdpIdSet(DdpC.REQ_ddpSelId, request);
+		} catch (Exception e) {
+			return rejectDryRun(request, "所选对象参数无效,请返回后重新选择。", requestId);
+		}
+		if (selectedObjectNames.isEmpty())
+			return rejectDryRun(request, "至少选择一个 FTS 根对象后才能执行只读预检。", requestId);
+
+		HttpSession session = request.getSession();
+		String selectionSessionKey = SELECTION_SESSION_PREFIX + requestId;
+		Object selectionValue = session.getAttribute(selectionSessionKey);
+		session.removeAttribute(selectionSessionKey);
+		if (!(selectionValue instanceof FtsRebuildSelectionB selection)
+				|| !selection.matches(pxmid, pxmhjid)
+				|| !selection.allowsAll(selectedObjectNames))
+			return rejectDryRun(request, "预检请求已过期或对象与目标项目不匹配,请重新进入重建页面。", requestId);
+
+		ProjectContext context = loadProjectContext(pxmid, pxmhjid, super.fetchDba());
+		PrjXs prjXs = PrjXs.fetchPrjXs(pxmhjid);
+		if (prjXs.pxmhj.getPxmid() != pxmid)
+			return rejectDryRun(request, "目标项目环境与项目不匹配,已停止预检。", requestId);
+
+		Fts fts = prjXs.fetchPrjFts();
+		FtsRebuildPlanB plan;
+		try (Db prjDba = prjXs.makePrjDba()) {
+			plan = new FtsRebuildPlanner().dryRun(requestId, pxmid, pxmhjid,
+					context.pxm, context.pxmhj, context.cfg.objMap,
+					selectedObjectNames, prjDba, fts);
+		}
+
+		session.setAttribute(PLAN_SESSION_PREFIX + requestId, plan);
+		request.setAttribute("ftsRebuildPlan", plan);
+		request.setAttribute("hasIdx", plan.getUnits());
+		return WebC.FWD_def;
+	}
+
+	@SuppressWarnings("unused")
+	public String rejectFtsRebuildWrite() {
+		HttpServletRequest request = super.req;
+		String requestId = request.getParameter("gxid");
+		if (requestId != null) {
+			HttpSession session = request.getSession();
+			session.removeAttribute("EXEC-SJK-" + requestId);
+			session.removeAttribute(SELECTION_SESSION_PREFIX + requestId);
+			session.removeAttribute(PLAN_SESSION_PREFIX + requestId);
+		}
+		request.setAttribute(ServC.REQ_msg,
+				"安全全量重建写入阶段尚未启用。当前入口只允许 Dry-run,未执行任何 Elasticsearch 写入。");
+		return WebC.FWD_def;
+	}
+
+	private static ProjectContext loadProjectContext(long pxmid, long pxmhjid, Db pmsDba) throws Exception {
+		PxmhjPo pxmhj = pmsDba.doSelPoById(pxmhjid, PxmhjPo.class, null);
+		if (pxmhj == null || pxmhj.getPxmid() != pxmid)
+			throw new IllegalArgumentException("目标项目环境不存在或不属于所选项目");
+
+		PxmPo pxm = pmsDba.doSelPoById(pxmid, PxmPo.class, null);
+		if (pxm == null)
+			throw new IllegalArgumentException("目标项目不存在");
+
+		PrjApp prjApp = new PrjApp();
+		prjApp.inDebug = RlsU.inDebugByPxmhjlb(pxmhj.getPxmhjlbm());
+		prjApp.name = pxm.getPxmh();
+		prjApp.desc = pxm.getMc();
+		CfgLoader cfg = PmsU.rdPrjCfgFileByType(pxmid, prjApp, pmsDba, PwjlbE.objXml.code);
+		return new ProjectContext(pxm, pxmhj, cfg);
+	}
+
+	private static long readLongParameter(HttpServletRequest request, String name) {
+		String value = request.getParameter(name);
+		if (value == null || !value.matches("[0-9]+"))
+			throw new IllegalArgumentException("参数 " + name + " 无效");
+		return Long.parseLong(value);
+	}
+
+	private static String rejectDryRun(HttpServletRequest request, String message, String requestId) {
+		if (requestId != null)
+			request.getSession().removeAttribute(SELECTION_SESSION_PREFIX + requestId);
+		request.setAttribute(ServC.REQ_msg, message);
+		request.setAttribute("ftsRebuildError", message);
+		request.setAttribute("hasIdx", List.of());
+		return WebC.FWD_def;
+	}
+
+	private record ProjectContext(PxmPo pxm, PxmhjPo pxmhj, CfgLoader cfg) {
+	}
+}

+ 4 - 1
src/core/cfg/impl/TimerLoader.java

@@ -15,6 +15,8 @@ import org.quartz.ScheduleBuilder;
 import org.quartz.Trigger;
 import org.quartz.TriggerBuilder;
 
+import java.util.TimeZone;
+
 import core.cfg.XmlLoader;
 import base.SsC;
 
@@ -143,7 +145,8 @@ public class TimerLoader extends XmlLoader {
 ///// 来自 WdSchedule 结构函数。Lin
 			/// 来自 WDCore_pms_product:QuartzUtils.createCronTrigger() 里的内容。Lin
 				/// 来自 WDCore_pms_product:QuartzUtils.createCronScheduleBuilder() 里的内容。Lin
-			CronScheduleBuilder scheBuilder = CronScheduleBuilder.cronSchedule(rule);	// (bean.rule)。Lin
+			CronScheduleBuilder scheBuilder = CronScheduleBuilder.cronSchedule(rule)
+					.inTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));	// (bean.rule)。Lin
 				///
 			bean.trigger = createTrigger(bean.name, bean.grpName, scheBuilder, false);
 			///

+ 156 - 0
src/core/fts/rebuild/FtsRebuildPlanB.java

@@ -0,0 +1,156 @@
+package core.fts.rebuild;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class FtsRebuildPlanB implements Serializable {
+
+	@Serial
+	private static final long serialVersionUID = 6119429360098249572L;
+
+	private final String planId;
+	private final String planChecksum;
+	private final String createdAt;
+	private final long pxmid;
+	private final long pxmhjid;
+	private final String projectName;
+	private final String environmentName;
+	private final String dbFingerprint;
+	private final String esFingerprint;
+	private final int configuredObjectCount;
+	private final int ftsCandidateCount;
+	private final int rootCandidateCount;
+	private final int logicalIndexCount;
+	private final List<String> selectedObjectNames;
+	private final List<FtsRebuildUnitB> units;
+	private final List<String> issues;
+	private final List<String> warnings;
+
+	public FtsRebuildPlanB(String planId, String planChecksum, String createdAt, long pxmid, long pxmhjid,
+			String projectName, String environmentName, String dbFingerprint, String esFingerprint,
+			int configuredObjectCount, int ftsCandidateCount, int rootCandidateCount, int logicalIndexCount,
+			List<String> selectedObjectNames, List<FtsRebuildUnitB> units,
+			List<String> issues, List<String> warnings) {
+		this.planId = planId;
+		this.planChecksum = planChecksum;
+		this.createdAt = createdAt;
+		this.pxmid = pxmid;
+		this.pxmhjid = pxmhjid;
+		this.projectName = projectName;
+		this.environmentName = environmentName;
+		this.dbFingerprint = dbFingerprint;
+		this.esFingerprint = esFingerprint;
+		this.configuredObjectCount = configuredObjectCount;
+		this.ftsCandidateCount = ftsCandidateCount;
+		this.rootCandidateCount = rootCandidateCount;
+		this.logicalIndexCount = logicalIndexCount;
+		this.selectedObjectNames = immutableCopy(selectedObjectNames);
+		this.units = Collections.unmodifiableList(new ArrayList<>(units));
+		this.issues = immutableCopy(issues);
+		this.warnings = immutableCopy(warnings);
+	}
+
+	private static List<String> immutableCopy(List<String> values) {
+		return Collections.unmodifiableList(new ArrayList<>(values));
+	}
+
+	public String getPlanId() {
+		return planId;
+	}
+
+	public String getPlanChecksum() {
+		return planChecksum;
+	}
+
+	public String getCreatedAt() {
+		return createdAt;
+	}
+
+	public long getPxmid() {
+		return pxmid;
+	}
+
+	public long getPxmhjid() {
+		return pxmhjid;
+	}
+
+	public String getProjectName() {
+		return projectName;
+	}
+
+	public String getEnvironmentName() {
+		return environmentName;
+	}
+
+	public String getDbFingerprint() {
+		return dbFingerprint;
+	}
+
+	public String getEsFingerprint() {
+		return esFingerprint;
+	}
+
+	public int getConfiguredObjectCount() {
+		return configuredObjectCount;
+	}
+
+	public int getFtsCandidateCount() {
+		return ftsCandidateCount;
+	}
+
+	public int getRootCandidateCount() {
+		return rootCandidateCount;
+	}
+
+	public int getLogicalIndexCount() {
+		return logicalIndexCount;
+	}
+
+	public List<String> getSelectedObjectNames() {
+		return selectedObjectNames;
+	}
+
+	public String getSelectedObjectNamesText() {
+		return String.join(", ", selectedObjectNames);
+	}
+
+	public List<FtsRebuildUnitB> getUnits() {
+		return units;
+	}
+
+	public int getSelectedLogicalIndexCount() {
+		return units.size();
+	}
+
+	public long getTotalDbCount() {
+		return units.stream().map(FtsRebuildUnitB::getDbCount)
+				.filter(value -> value != null).mapToLong(Long::longValue).sum();
+	}
+
+	public List<String> getIssues() {
+		return issues;
+	}
+
+	public String getIssuesText() {
+		return issues.isEmpty() ? "无" : String.join(";", issues);
+	}
+
+	public List<String> getWarnings() {
+		return warnings;
+	}
+
+	public String getWarningsText() {
+		return warnings.isEmpty() ? "无" : String.join(";", warnings);
+	}
+
+	public boolean isBlocked() {
+		return !issues.isEmpty() || units.stream().anyMatch(FtsRebuildUnitB::isBlocked);
+	}
+
+	public String getStatus() {
+		return isBlocked() ? "PREFLIGHT_BLOCKED" : "DRY_RUN_COMPLETED";
+	}
+}

+ 212 - 0
src/core/fts/rebuild/FtsRebuildPlanner.java

@@ -0,0 +1,212 @@
+package core.fts.rebuild;
+
+import base.po.PxmPo;
+import base.po.PxmhjPo;
+import ss.db.Db;
+import ss.fts.Fts;
+import ss.fts.FtsInfoB;
+import ss.fts.FtsU;
+import ss.obj.ObjB;
+import ss.obj.ObjC;
+
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import java.util.regex.Pattern;
+import java.util.stream.Stream;
+
+public class FtsRebuildPlanner {
+
+	private static final Pattern SQL_IDENTIFIER =
+			Pattern.compile("[A-Za-z][A-Za-z0-9_$#]*(\\.[A-Za-z][A-Za-z0-9_$#]*)*");
+	private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
+	private static final DateTimeFormatter INDEX_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
+
+	public FtsRebuildPlanB dryRun(String planId, long pxmid, long pxmhjid, PxmPo pxm, PxmhjPo pxmhj,
+			Map<String, ObjB> objMap, Set<String> selectedObjectNames, Db prjDba, Fts fts) {
+		List<String> issues = new ArrayList<>();
+		List<String> warnings = new ArrayList<>();
+		List<String> selectedNames = selectedObjectNames.stream().sorted().toList();
+		List<ObjB> rootCandidates = objMap.values().stream()
+				.filter(obj -> obj.hasFts && obj.isRoot)
+				.sorted(Comparator.comparing(obj -> obj.name))
+				.toList();
+		int ftsCandidateCount = (int) objMap.values().stream().filter(obj -> obj.hasFts).count();
+		Set<String> allLogicalIndexes = new TreeSet<>();
+		List<String> noFieldObjects = new ArrayList<>();
+		for (ObjB obj : rootCandidates) {
+			allLogicalIndexes.add(FtsU.rdFtsIdxName(obj));
+			if (obj.searchFieldList.isEmpty() && obj.keywordFieldList.isEmpty())
+				noFieldObjects.add(obj.name);
+		}
+		if (!noFieldObjects.isEmpty())
+			warnings.add("全部根候选中没有搜索字段的对象:" + String.join(", ", noFieldObjects));
+
+		Map<String, List<ObjB>> groupedObjects = new TreeMap<>();
+		for (String objectName : selectedNames) {
+			ObjB obj = objMap.get(objectName);
+			if (obj == null) {
+				issues.add("目标项目配置中不存在对象 " + objectName);
+				continue;
+			}
+			if (!obj.hasFts || !obj.isRoot) {
+				issues.add("对象 " + objectName + " 不是可重建的根 FTS 对象");
+				continue;
+			}
+			groupedObjects.computeIfAbsent(FtsU.rdFtsIdxName(obj), key -> new ArrayList<>()).add(obj);
+		}
+		if (groupedObjects.isEmpty())
+			issues.add("没有可执行只读预检的逻辑索引");
+
+		String esFingerprint = mask(pxmhj.getFtszh()) + "@" + pxmhj.getFtsdz() + ":" + pxmhj.getFtsdk();
+		boolean esAvailable = false;
+		try {
+			FtsInfoB info = fts.rdInfo();
+			esFingerprint += "/" + info.getClusterName() + "(" + info.getClusterUuid() + ")/" + info.getVersion();
+			esAvailable = true;
+		} catch (Exception e) {
+			issues.add("无法读取目标 Elasticsearch 集群信息:" + safeMessage(e));
+		}
+
+		String indexTime = LocalDateTime.now().format(INDEX_TIME_FORMAT);
+		List<FtsRebuildUnitB> units = new ArrayList<>();
+		for (Map.Entry<String, List<ObjB>> entry : groupedObjects.entrySet()) {
+			units.add(makeUnit(entry.getKey(), entry.getValue(), indexTime, planId,
+					objMap, prjDba, fts, esAvailable));
+		}
+
+		String createdAt = LocalDateTime.now().format(TIME_FORMAT);
+		String projectName = pxm.getMc() + "(" + pxm.getPxmh() + ")";
+		String environmentName = "项目环境ID=" + pxmhjid + ",类别码=" + pxmhj.getPxmhjlbm();
+		String dbFingerprint = mask(pxmhj.getDbzh()) + "@" + pxmhj.getDbdz() + ":" +
+				pxmhj.getDbdk() + "/" + pxmhj.getDbslm();
+		String checksum = checksum(planId, pxmid, pxmhjid, dbFingerprint, esFingerprint,
+				selectedNames, units, issues, warnings);
+		return new FtsRebuildPlanB(planId, checksum, createdAt, pxmid, pxmhjid, projectName,
+				environmentName, dbFingerprint, esFingerprint, objMap.size(), ftsCandidateCount,
+				rootCandidates.size(), allLogicalIndexes.size(), selectedNames, units, issues, warnings);
+	}
+
+	private FtsRebuildUnitB makeUnit(String logicalIndexName, List<ObjB> sourceObjects,
+			String indexTime, String planId, Map<String, ObjB> objMap, Db prjDba, Fts fts,
+			boolean esAvailable) {
+		List<String> issues = new ArrayList<>();
+		List<String> warnings = new ArrayList<>();
+		List<String> sourceNames = sourceObjects.stream().map(obj -> obj.name).sorted().toList();
+		Set<String> canonicalNames = new TreeSet<>();
+		for (ObjB sourceObject : sourceObjects)
+			canonicalNames.add(FtsU.rdFtsObjName(sourceObject));
+		if (canonicalNames.size() != 1)
+			issues.add("同一逻辑索引映射到多个 canonical 对象:" + String.join(", ", canonicalNames));
+
+		String canonicalName = canonicalNames.isEmpty() ? logicalIndexName : canonicalNames.iterator().next();
+		ObjB canonicalObject = sourceObjects.isEmpty() ? null : FtsU.rdFtsObj(sourceObjects.get(0), objMap);
+		if (canonicalObject == null)
+			issues.add("目标项目配置中不存在 canonical 对象 " + canonicalName);
+
+		String canonicalDesc = canonicalObject == null ? "" : canonicalObject.desc;
+		String tableName = canonicalObject == null ? "" : canonicalObject.tabName;
+		String idFieldName = canonicalObject == null ? "" : canonicalObject.idName;
+		List<String> fieldNames = canonicalObject == null ? new ArrayList<>() : fieldNames(canonicalObject);
+		if (canonicalObject != null && canonicalObject.searchFieldList.isEmpty()
+				&& canonicalObject.keywordFieldList.isEmpty())
+			issues.add("canonical 对象没有定义任何 search 或 keyword 字段");
+		if (!isIdentifier(tableName))
+			issues.add("数据表名不符合安全标识符规则:" + tableName);
+		if (!isIdentifier(idFieldName))
+			issues.add("主键字段不符合安全标识符规则:" + idFieldName);
+		for (String fieldName : fieldNames) {
+			if (!isIdentifier(fieldName))
+				issues.add("FTS 字段不符合安全标识符规则:" + fieldName);
+		}
+
+		Long dbCount = null;
+		if (canonicalObject != null && isIdentifier(tableName) && isIdentifier(idFieldName)) {
+			try {
+				Object countValue = prjDba.doSelField("select count(*) from " + tableName +
+						" where " + ObjC.JLZT_useStr);
+				dbCount = countValue instanceof Number number ? number.longValue() :
+						Long.parseLong(String.valueOf(countValue));
+			} catch (Exception e) {
+				issues.add("目标项目数据库数量查询失败:" + safeMessage(e));
+			}
+		}
+
+		boolean existingIndex = false;
+		if (esAvailable) {
+			try {
+				existingIndex = fts.hasIdx(logicalIndexName);
+				if (!existingIndex)
+					warnings.add("当前稳定逻辑索引不存在,后续需按首次创建流程处理");
+			} catch (Exception e) {
+				issues.add("目标 Elasticsearch 索引检查失败:" + safeMessage(e));
+			}
+		}
+		if (sourceNames.size() > 1 || !sourceNames.contains(canonicalName))
+			warnings.add("已按逻辑索引归并到 canonical 对象 " + canonicalName);
+
+		String shortPlanId = planId.length() <= 8 ? planId : planId.substring(0, 8);
+		String physicalIndexName = logicalIndexName + "_v" + indexTime + "_" + shortPlanId;
+		return new FtsRebuildUnitB(logicalIndexName, physicalIndexName, sourceNames,
+				canonicalName, canonicalDesc, tableName, idFieldName, fieldNames, dbCount,
+				existingIndex, issues, warnings);
+	}
+
+	private static List<String> fieldNames(ObjB obj) {
+		Set<String> fields = new LinkedHashSet<>();
+		fields.add(obj.idName);
+		Stream.of(obj.searchFieldList, obj.keywordFieldList)
+				.flatMap(List::stream).map(field -> field.name).forEach(fields::add);
+		return fields.stream().sorted().toList();
+	}
+
+	private static boolean isIdentifier(String value) {
+		return value != null && SQL_IDENTIFIER.matcher(value).matches();
+	}
+
+	private static String mask(String value) {
+		if (value == null || value.isBlank())
+			return "未配置";
+		return value.substring(0, 1) + "***";
+	}
+
+	private static String safeMessage(Exception exception) {
+		String message = exception.getMessage();
+		return message == null || message.isBlank() ? exception.getClass().getSimpleName() : message;
+	}
+
+	private static String checksum(String planId, long pxmid, long pxmhjid, String dbFingerprint,
+			String esFingerprint, List<String> selectedNames, List<FtsRebuildUnitB> units,
+			List<String> issues, List<String> warnings) {
+		StringBuilder source = new StringBuilder(planId).append('|').append(pxmid).append('|')
+				.append(pxmhjid).append('|').append(dbFingerprint).append('|').append(esFingerprint)
+				.append('|').append(String.join(",", selectedNames));
+		for (FtsRebuildUnitB unit : units) {
+			source.append('|').append(unit.getLogicalIndexName()).append('|')
+					.append(unit.getCanonicalObjectName()).append('|').append(unit.getTableName())
+					.append('|').append(unit.getIdFieldName()).append('|').append(unit.getFieldNamesText())
+					.append('|').append(unit.getDbCountText()).append('|').append(unit.isExistingIndex())
+					.append('|').append(unit.getIssuesText()).append('|').append(unit.getWarningsText());
+		}
+		source.append('|').append(String.join(";", issues)).append('|').append(String.join(";", warnings));
+		try {
+			MessageDigest digest = MessageDigest.getInstance("SHA-256");
+			byte[] bytes = digest.digest(source.toString().getBytes(StandardCharsets.UTF_8));
+			StringBuilder result = new StringBuilder();
+			for (byte value : bytes)
+				result.append(String.format("%02x", value));
+			return result.toString();
+		} catch (Exception e) {
+			throw new IllegalStateException("无法生成 FTS 重建计划校验和", e);
+		}
+	}
+}

+ 31 - 0
src/core/fts/rebuild/FtsRebuildSelectionB.java

@@ -0,0 +1,31 @@
+package core.fts.rebuild;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.util.Collections;
+import java.util.Set;
+import java.util.TreeSet;
+
+public class FtsRebuildSelectionB implements Serializable {
+
+	@Serial
+	private static final long serialVersionUID = -5095361879425404044L;
+
+	private final long pxmid;
+	private final long pxmhjid;
+	private final Set<String> allowedObjectNames;
+
+	public FtsRebuildSelectionB(long pxmid, long pxmhjid, Set<String> allowedObjectNames) {
+		this.pxmid = pxmid;
+		this.pxmhjid = pxmhjid;
+		this.allowedObjectNames = Collections.unmodifiableSet(new TreeSet<>(allowedObjectNames));
+	}
+
+	public boolean matches(long pxmid, long pxmhjid) {
+		return this.pxmid == pxmid && this.pxmhjid == pxmhjid;
+	}
+
+	public boolean allowsAll(Set<String> objectNames) {
+		return allowedObjectNames.containsAll(objectNames);
+	}
+}

+ 128 - 0
src/core/fts/rebuild/FtsRebuildUnitB.java

@@ -0,0 +1,128 @@
+package core.fts.rebuild;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class FtsRebuildUnitB implements Serializable {
+
+	@Serial
+	private static final long serialVersionUID = -2431383552425903652L;
+
+	private final String logicalIndexName;
+	private final String physicalIndexName;
+	private final List<String> sourceObjectNames;
+	private final String canonicalObjectName;
+	private final String canonicalObjectDesc;
+	private final String tableName;
+	private final String idFieldName;
+	private final List<String> fieldNames;
+	private final Long dbCount;
+	private final boolean existingIndex;
+	private final List<String> issues;
+	private final List<String> warnings;
+
+	public FtsRebuildUnitB(String logicalIndexName, String physicalIndexName,
+			List<String> sourceObjectNames, String canonicalObjectName, String canonicalObjectDesc,
+			String tableName, String idFieldName, List<String> fieldNames, Long dbCount,
+			boolean existingIndex, List<String> issues, List<String> warnings) {
+		this.logicalIndexName = logicalIndexName;
+		this.physicalIndexName = physicalIndexName;
+		this.sourceObjectNames = immutableCopy(sourceObjectNames);
+		this.canonicalObjectName = canonicalObjectName;
+		this.canonicalObjectDesc = canonicalObjectDesc;
+		this.tableName = tableName;
+		this.idFieldName = idFieldName;
+		this.fieldNames = immutableCopy(fieldNames);
+		this.dbCount = dbCount;
+		this.existingIndex = existingIndex;
+		this.issues = immutableCopy(issues);
+		this.warnings = immutableCopy(warnings);
+	}
+
+	private static List<String> immutableCopy(List<String> values) {
+		return Collections.unmodifiableList(new ArrayList<>(values));
+	}
+
+	public String getLogicalIndexName() {
+		return logicalIndexName;
+	}
+
+	public String getPhysicalIndexName() {
+		return physicalIndexName;
+	}
+
+	public List<String> getSourceObjectNames() {
+		return sourceObjectNames;
+	}
+
+	public String getSourceObjectNamesText() {
+		return String.join(", ", sourceObjectNames);
+	}
+
+	public String getCanonicalObjectName() {
+		return canonicalObjectName;
+	}
+
+	public String getCanonicalObjectDesc() {
+		return canonicalObjectDesc;
+	}
+
+	public String getTableName() {
+		return tableName;
+	}
+
+	public String getIdFieldName() {
+		return idFieldName;
+	}
+
+	public List<String> getFieldNames() {
+		return fieldNames;
+	}
+
+	public String getFieldNamesText() {
+		return String.join(", ", fieldNames);
+	}
+
+	public Long getDbCount() {
+		return dbCount;
+	}
+
+	public String getDbCountText() {
+		return dbCount == null ? "未取得" : String.valueOf(dbCount);
+	}
+
+	public boolean isExistingIndex() {
+		return existingIndex;
+	}
+
+	public String getExistingIndexText() {
+		return existingIndex ? "已存在" : "不存在";
+	}
+
+	public List<String> getIssues() {
+		return issues;
+	}
+
+	public String getIssuesText() {
+		return issues.isEmpty() ? "无" : String.join(";", issues);
+	}
+
+	public List<String> getWarnings() {
+		return warnings;
+	}
+
+	public String getWarningsText() {
+		return warnings.isEmpty() ? "无" : String.join(";", warnings);
+	}
+
+	public boolean isBlocked() {
+		return !issues.isEmpty();
+	}
+
+	public String getStatus() {
+		return isBlocked() ? "BLOCKED" : "DRY_RUN_READY";
+	}
+}

+ 9 - 0
src/ss/fts/Fts.java

@@ -1322,6 +1322,15 @@ public class Fts implements AutoCloseable {
 	}
 
 
+	public FtsInfoB rdInfo() throws IOException {
+		if (this.conn == null)
+			throw new IOException("没有连接 FTS");
+
+		InfoResponse info = this.conn.info();
+		return new FtsInfoB(info.clusterName(), info.clusterUuid(), info.version().number());
+	}
+
+
 // --- 不用连接池 FtsPool。Lin
 
 	// 增加,为了 PrjXs.makePrjFts()。Lin

+ 26 - 0
src/ss/fts/FtsInfoB.java

@@ -0,0 +1,26 @@
+package ss.fts;
+
+public class FtsInfoB {
+
+	private final String clusterName;
+	private final String clusterUuid;
+	private final String version;
+
+	public FtsInfoB(String clusterName, String clusterUuid, String version) {
+		this.clusterName = clusterName;
+		this.clusterUuid = clusterUuid;
+		this.version = version;
+	}
+
+	public String getClusterName() {
+		return clusterName;
+	}
+
+	public String getClusterUuid() {
+		return clusterUuid;
+	}
+
+	public String getVersion() {
+		return version;
+	}
+}

+ 8 - 0
src/ss/fts/FtsU.java

@@ -191,4 +191,12 @@ public class FtsU {
 		return vo;
 	}
 
+
+	public static ObjB rdFtsObj(ObjB vo, Map<String, ObjB> objMap) {
+		if (StringUtils.isNotBlank(vo.ftsObjName))
+			return objMap.get(vo.ftsObjName);
+
+		return vo;
+	}
+
 }

+ 524 - 0
tools/FtsDryRunInventory.java

@@ -0,0 +1,524 @@
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+import javax.xml.parsers.DocumentBuilderFactory;
+import java.net.URI;
+import java.net.URLEncoder;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.Statement;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.Base64;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Stream;
+
+public class FtsDryRunInventory {
+
+	private static final Pattern JAVA_STRING_ASSIGNMENT =
+			Pattern.compile("super\\.(tabName|idName)\\s*=\\s*\"([^\"]+)\"");
+	private static final Pattern SAFE_IDENTIFIER =
+			Pattern.compile("[A-Za-z][A-Za-z0-9_$#]*(\\.[A-Za-z][A-Za-z0-9_$#]*)*");
+	private static final Pattern JSON_NUMBER = Pattern.compile("\"%s\"\\s*:\\s*([0-9]+)");
+	private static final Pattern JSON_STRING = Pattern.compile("\"%s\"\\s*:\\s*\"([^\"]*)\"");
+	private static final Pattern CHILD_OBJECT_NAME =
+			Pattern.compile("[\"']name[\"']\\s*:\\s*[\"']([^\"']+)[\"']");
+	private static final Pattern CHILD_ARRAY_STRING =
+			Pattern.compile("(?:\\[|,)\\s*[\"']([^\"']+)[\"']\\s*(?=,|\\])");
+	private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
+	private static final String RECORD_FILTER = "JLZTM in (51,22,25)";
+
+	public static void main(String[] args) throws Exception {
+		if (args.length != 10) {
+			System.err.println("Usage: FtsDryRunInventory <cfgRoot> <srcRoot> <jdbcUrl> <dbUser> " +
+					"<dbPasswordEnv> <esBaseUrl> <esUser> <esPasswordEnv> <markdownOutput> <tsvOutput>");
+			System.exit(64);
+		}
+
+		Path cfgRoot = Path.of(args[0]);
+		Path srcRoot = Path.of(args[1]);
+		String dbPassword = requiredEnvironment(args[4]);
+		String esPassword = requiredEnvironment(args[7]);
+		Path markdownOutput = Path.of(args[8]);
+		Path tsvOutput = Path.of(args[9]);
+
+		Inventory inventory = loadInventory(cfgRoot, srcRoot);
+		EsProbe esProbe = new EsProbe(args[5], args[6], esPassword);
+		EsEnvironment esEnvironment = esProbe.readEnvironment();
+
+		Class.forName("oracle.jdbc.OracleDriver");
+		try (Connection connection = DriverManager.getConnection(args[2], args[3], dbPassword)) {
+			connection.setAutoCommit(false);
+			connection.setReadOnly(true);
+			for (RebuildUnit unit : inventory.units)
+				probeUnit(connection, esProbe, unit);
+			connection.rollback();
+		}
+
+		String createdAt = LocalDateTime.now().format(TIME_FORMAT);
+		String markdown = makeMarkdown(createdAt, args[2], args[3], args[5], inventory, esEnvironment);
+		String tsv = makeTsv(inventory.units);
+		Files.createDirectories(markdownOutput.toAbsolutePath().getParent());
+		Files.createDirectories(tsvOutput.toAbsolutePath().getParent());
+		Files.writeString(markdownOutput, markdown, StandardCharsets.UTF_8);
+		Files.writeString(tsvOutput, tsv, StandardCharsets.UTF_8);
+
+		long blocked = inventory.units.stream().filter(RebuildUnit::blocked).count();
+		long mismatched = inventory.units.stream().filter(RebuildUnit::countMismatch).count();
+		System.out.println("DRY_RUN_COMPLETED objects=" + inventory.configuredObjectCount +
+				" ftsCandidates=" + inventory.ftsCandidateCount +
+				" rootCandidates=" + inventory.rootCandidateCount +
+				" logicalIndexes=" + inventory.units.size() +
+				" blocked=" + blocked + " countMismatch=" + mismatched);
+		System.out.println("MARKDOWN=" + markdownOutput.toAbsolutePath());
+		System.out.println("TSV=" + tsvOutput.toAbsolutePath());
+	}
+
+	private static Inventory loadInventory(Path cfgRoot, Path srcRoot) throws Exception {
+		Map<String, ObjectConfig> objectMap = new LinkedHashMap<>();
+		List<String> globalIssues = new ArrayList<>();
+		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+		factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
+		factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
+		factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
+		factory.setXIncludeAware(false);
+		factory.setExpandEntityReferences(false);
+
+		List<Path> xmlFiles;
+		try (Stream<Path> paths = Files.walk(cfgRoot)) {
+			xmlFiles = paths.filter(path -> path.getFileName().toString().endsWith(".obj.xml"))
+					.sorted().toList();
+		}
+		for (Path xmlFile : xmlFiles) {
+			Document document = factory.newDocumentBuilder().parse(xmlFile.toFile());
+			NodeList nodes = document.getElementsByTagName("obj");
+			for (int index = 0; index < nodes.getLength(); index++) {
+				Element element = (Element) nodes.item(index);
+				ObjectConfig object = readObject(element, xmlFile, srcRoot);
+				ObjectConfig previous = objectMap.put(object.name, object);
+				if (previous != null)
+					globalIssues.add("对象名重复:" + object.name + ",文件 " + previous.xmlFile + " 与 " + xmlFile);
+			}
+		}
+
+		Set<String> referencedChildren = new LinkedHashSet<>();
+		for (ObjectConfig object : objectMap.values()) {
+			for (String childName : childNames(object.childStr)) {
+				if (objectMap.containsKey(childName))
+					referencedChildren.add(childName);
+			}
+		}
+
+		List<ObjectConfig> rootCandidates = objectMap.values().stream()
+				.filter(object -> object.hasFts && object.root && !referencedChildren.contains(object.name))
+				.sorted(Comparator.comparing(object -> object.name))
+				.toList();
+		Map<String, List<ObjectConfig>> grouped = new TreeMap<>();
+		for (ObjectConfig object : rootCandidates)
+			grouped.computeIfAbsent(object.logicalIndex, key -> new ArrayList<>()).add(object);
+
+		List<RebuildUnit> units = new ArrayList<>();
+		for (Map.Entry<String, List<ObjectConfig>> entry : grouped.entrySet()) {
+			List<ObjectConfig> sources = entry.getValue();
+			Set<String> canonicalNames = new LinkedHashSet<>();
+			for (ObjectConfig source : sources)
+				canonicalNames.add(source.canonicalName);
+			String canonicalName = canonicalNames.iterator().next();
+			ObjectConfig canonical = objectMap.get(canonicalName);
+			RebuildUnit unit = new RebuildUnit(entry.getKey(), sources, canonicalName, canonical);
+			if (canonicalNames.size() != 1)
+				unit.issues.add("同一逻辑索引存在多个 canonical 对象:" + String.join(", ", canonicalNames));
+			if (canonical == null)
+				unit.issues.add("配置中找不到 canonical 对象 " + canonicalName);
+			else {
+				if (canonical.searchFields.isEmpty() && canonical.keywordFields.isEmpty())
+					unit.issues.add("canonical 对象没有 search/keyword 字段");
+				if (!safeIdentifier(canonical.tableName))
+					unit.issues.add("表名不符合安全标识符规则:" + canonical.tableName);
+				if (!safeIdentifier(canonical.idName))
+					unit.issues.add("主键不符合安全标识符规则:" + canonical.idName);
+				for (String field : canonical.allFields()) {
+					if (!safeIdentifier(field))
+						unit.issues.add("字段不符合安全标识符规则:" + field);
+				}
+			}
+			if (sources.size() > 1 || !sources.stream().anyMatch(source -> source.name.equals(canonicalName)))
+				unit.warnings.add("多个来源对象归并到 canonical 对象 " + canonicalName);
+			units.add(unit);
+		}
+		int ftsCandidateCount = (int) objectMap.values().stream().filter(object -> object.hasFts).count();
+		return new Inventory(objectMap.size(), ftsCandidateCount, rootCandidates.size(), units, globalIssues);
+	}
+
+	private static ObjectConfig readObject(Element element, Path xmlFile, Path srcRoot) throws Exception {
+		String name = requiredAttribute(element, "name", xmlFile);
+		String description = element.getAttribute("desc");
+		String poClass = element.getAttribute("po");
+		String fts = element.getAttribute("fts");
+		boolean hasFts = !"false".equalsIgnoreCase(fts);
+		boolean root = !"child".equalsIgnoreCase(element.getAttribute("lvl"));
+		String childStr = element.getAttribute("child");
+		String canonicalName = fts.isBlank() || "true".equalsIgnoreCase(fts) ? name : fts;
+		String logicalIndex = canonicalName.toLowerCase(Locale.ROOT);
+		List<String> searchFields = splitFields(element.getAttribute("search"));
+		List<String> keywordFields = splitFields(element.getAttribute("keyword"));
+		String tableName = "";
+		String idName = "";
+		if (!poClass.isBlank()) {
+			Path poSource = srcRoot.resolve(poClass.replace('.', '/') + ".java");
+			if (Files.isRegularFile(poSource)) {
+				String source = Files.readString(poSource, StandardCharsets.UTF_8);
+				Matcher matcher = JAVA_STRING_ASSIGNMENT.matcher(source);
+				while (matcher.find()) {
+					if ("tabName".equals(matcher.group(1)))
+						tableName = matcher.group(2);
+					else if ("idName".equals(matcher.group(1)))
+						idName = matcher.group(2);
+				}
+			}
+		}
+		return new ObjectConfig(name, description, poClass, tableName, idName, canonicalName,
+				logicalIndex, searchFields, keywordFields, hasFts, root, childStr, xmlFile.toString());
+	}
+
+	private static Set<String> childNames(String childStr) {
+		Set<String> names = new LinkedHashSet<>();
+		if (childStr == null || childStr.isBlank())
+			return names;
+		if (!childStr.contains("[")) {
+			for (String value : childStr.split(",")) {
+				String name = value.trim();
+				if (!name.isEmpty())
+					names.add(name);
+			}
+			return names;
+		}
+		Matcher objectMatcher = CHILD_OBJECT_NAME.matcher(childStr);
+		while (objectMatcher.find())
+			names.add(objectMatcher.group(1).trim());
+		Matcher stringMatcher = CHILD_ARRAY_STRING.matcher(childStr);
+		while (stringMatcher.find())
+			names.add(stringMatcher.group(1).trim());
+		return names;
+	}
+
+	private static void probeUnit(Connection connection, EsProbe esProbe, RebuildUnit unit) {
+		ObjectConfig canonical = unit.canonical;
+		if (canonical != null && safeIdentifier(canonical.tableName) && safeIdentifier(canonical.idName)) {
+			try (Statement statement = connection.createStatement()) {
+				statement.setQueryTimeout(60);
+				try (ResultSet resultSet = statement.executeQuery("select * from " + canonical.tableName + " where 1=0")) {
+					ResultSetMetaData metadata = resultSet.getMetaData();
+					Set<String> columns = new LinkedHashSet<>();
+					for (int index = 1; index <= metadata.getColumnCount(); index++)
+						columns.add(metadata.getColumnName(index).toLowerCase(Locale.ROOT));
+					if (!columns.contains("jlztm"))
+						unit.issues.add("目标表缺少 JLZTM,无法使用统一记录状态口径");
+					for (String field : canonical.allFields()) {
+						if (!columns.contains(field.toLowerCase(Locale.ROOT)))
+							unit.issues.add("目标表缺少索引字段 " + field);
+					}
+				}
+				if (unit.issues.stream().noneMatch(issue -> issue.contains("JLZTM"))) {
+					try (ResultSet resultSet = statement.executeQuery("select count(*) from " + canonical.tableName +
+							" where " + RECORD_FILTER)) {
+						if (resultSet.next())
+							unit.dbCount = resultSet.getLong(1);
+					}
+				}
+			} catch (Exception exception) {
+				unit.issues.add("数据库只读检查失败:" + safeMessage(exception));
+			}
+		}
+
+		try {
+			unit.esExists = esProbe.indexExists(unit.logicalIndex);
+			if (unit.esExists)
+				unit.esCount = esProbe.indexCount(unit.logicalIndex);
+			else
+				unit.warnings.add("当前 Elasticsearch 中不存在该逻辑索引");
+		} catch (Exception exception) {
+			unit.issues.add("Elasticsearch 只读检查失败:" + safeMessage(exception));
+		}
+		if (unit.countMismatch())
+			unit.warnings.add("数据库数量与当前索引文档数不一致,差值=" + (unit.dbCount - unit.esCount));
+	}
+
+	private static String makeMarkdown(String createdAt, String jdbcUrl, String dbUser, String esBaseUrl,
+			Inventory inventory, EsEnvironment esEnvironment) {
+		long blocked = inventory.units.stream().filter(RebuildUnit::blocked).count();
+		long mismatch = inventory.units.stream().filter(RebuildUnit::countMismatch).count();
+		long dbTotal = inventory.units.stream().filter(unit -> unit.dbCount != null).mapToLong(unit -> unit.dbCount).sum();
+		long esTotal = inventory.units.stream().filter(unit -> unit.esCount != null).mapToLong(unit -> unit.esCount).sum();
+		StringBuilder result = new StringBuilder();
+		result.append("# Elasticsearch 全选 Dry-run 运行报告\n\n")
+				.append("> 生成时间:").append(createdAt).append("  \n")
+				.append("> 安全边界:仅执行 Oracle `SELECT` 和 Elasticsearch `GET/HEAD`;未创建、删除、写入或切换索引。\n\n")
+				.append("## 环境指纹\n\n")
+				.append("- 数据库:`").append(maskUser(dbUser)).append("@").append(safeMarkdown(jdbcUrl)).append("`\n")
+				.append("- Elasticsearch:`").append(safeMarkdown(esBaseUrl)).append("`\n")
+				.append("- 集群:`").append(safeMarkdown(esEnvironment.clusterName)).append("`,UUID `")
+				.append(safeMarkdown(esEnvironment.clusterUuid)).append("`,版本 `")
+				.append(safeMarkdown(esEnvironment.version)).append("`\n")
+				.append("- 集群健康:`").append(safeMarkdown(esEnvironment.health)).append("`\n")
+				.append("- IK 插件:").append(esEnvironment.hasIk ? "已发现 `analysis-ik`" : "**未发现 `analysis-ik`**").append("\n\n")
+				.append("## 汇总\n\n")
+				.append("| 指标 | 数量 |\n|---|---:|\n")
+				.append("| 配置对象 | ").append(inventory.configuredObjectCount).append(" |\n")
+				.append("| FTS 候选 | ").append(inventory.ftsCandidateCount).append(" |\n")
+				.append("| 根候选 | ").append(inventory.rootCandidateCount).append(" |\n")
+				.append("| 逻辑索引 | ").append(inventory.units.size()).append(" |\n")
+				.append("| BLOCKED | ").append(blocked).append(" |\n")
+				.append("| 数量不一致 | ").append(mismatch).append(" |\n")
+				.append("| 已取得数据库记录合计 | ").append(dbTotal).append(" |\n")
+				.append("| 已取得 ES 文档合计 | ").append(esTotal).append(" |\n\n")
+				.append("记录过滤口径:`").append(RECORD_FILTER).append("`。\n\n");
+		if (!inventory.globalIssues.isEmpty()) {
+			result.append("## 全局问题\n\n");
+			for (String issue : inventory.globalIssues)
+				result.append("- ").append(safeMarkdown(issue)).append("\n");
+			result.append("\n");
+		}
+		result.append("## 逐逻辑索引结果\n\n")
+				.append("| 状态 | 逻辑索引 | 来源对象 | canonical | 表/主键 | 字段 | DB | ES | 差值 | 问题/警告 |\n")
+				.append("|---|---|---|---|---|---|---:|---:|---:|---|\n");
+		for (RebuildUnit unit : inventory.units) {
+			Long delta = unit.dbCount == null || unit.esCount == null ? null : unit.dbCount - unit.esCount;
+			result.append("| ").append(unit.blocked() ? "BLOCKED" : "DRY_RUN_READY")
+					.append(" | `").append(unit.logicalIndex).append("` | ")
+					.append(safeMarkdown(unit.sourceNames())).append(" | `")
+					.append(safeMarkdown(unit.canonicalName)).append("` | `")
+					.append(safeMarkdown(unit.tableAndId())).append("` | ")
+					.append(safeMarkdown(unit.fields())).append(" | ")
+					.append(nullable(unit.dbCount)).append(" | ")
+					.append(nullable(unit.esCount)).append(" | ")
+					.append(nullable(delta)).append(" | ")
+					.append(safeMarkdown(unit.messages())).append(" |\n");
+		}
+		result.append("\n## 结论\n\n");
+		if (blocked > 0 || !inventory.globalIssues.isEmpty() || !esEnvironment.hasIk || "red".equals(esEnvironment.health))
+			result.append("当前结果为 **No-Go**:必须先关闭全部阻断项,再进入任何 Elasticsearch 写入阶段。\n");
+		else
+			result.append("当前只读预检无阻断项;仍需完成分页 Bulk、校验、alias 和回滚能力后才能进入写入演练。\n");
+		return result.toString();
+	}
+
+	private static String makeTsv(List<RebuildUnit> units) {
+		StringBuilder result = new StringBuilder("status\tlogical_index\tsource_objects\tcanonical_object\ttable\tid_field\tfields\tdb_count\tes_exists\tes_count\tdelta\tissues\twarnings\n");
+		for (RebuildUnit unit : units) {
+			Long delta = unit.dbCount == null || unit.esCount == null ? null : unit.dbCount - unit.esCount;
+			result.append(unit.blocked() ? "BLOCKED" : "DRY_RUN_READY").append('\t')
+					.append(tsv(unit.logicalIndex)).append('\t').append(tsv(unit.sourceNames())).append('\t')
+					.append(tsv(unit.canonicalName)).append('\t')
+					.append(tsv(unit.canonical == null ? "" : unit.canonical.tableName)).append('\t')
+					.append(tsv(unit.canonical == null ? "" : unit.canonical.idName)).append('\t')
+					.append(tsv(unit.fields())).append('\t').append(nullable(unit.dbCount)).append('\t')
+					.append(unit.esExists).append('\t').append(nullable(unit.esCount)).append('\t')
+					.append(nullable(delta)).append('\t').append(tsv(String.join(";", unit.issues))).append('\t')
+					.append(tsv(String.join(";", unit.warnings))).append('\n');
+		}
+		return result.toString();
+	}
+
+	private static String requiredEnvironment(String name) {
+		String value = System.getenv(name);
+		if (value == null || value.isBlank())
+			throw new IllegalArgumentException("Missing environment variable " + name);
+		return value;
+	}
+
+	private static String requiredAttribute(Element element, String name, Path file) {
+		String value = element.getAttribute(name);
+		if (value.isBlank())
+			throw new IllegalArgumentException("Missing " + name + " in " + file);
+		return value;
+	}
+
+	private static List<String> splitFields(String value) {
+		if (value == null || value.isBlank())
+			return List.of();
+		List<String> result = new ArrayList<>();
+		for (String item : value.split(",")) {
+			String field = item.trim();
+			if (!field.isBlank())
+				result.add(field);
+		}
+		return result;
+	}
+
+	private static boolean safeIdentifier(String value) {
+		return value != null && SAFE_IDENTIFIER.matcher(value).matches();
+	}
+
+	private static String safeMessage(Exception exception) {
+		String message = exception.getMessage();
+		return message == null || message.isBlank() ? exception.getClass().getSimpleName() : message.replace('\r', ' ').replace('\n', ' ');
+	}
+
+	private static String safeMarkdown(String value) {
+		return value == null ? "" : value.replace("|", "\\|").replace("\r", " ").replace("\n", " ");
+	}
+
+	private static String maskUser(String value) {
+		return value == null || value.isBlank() ? "未配置" : value.substring(0, 1) + "***";
+	}
+
+	private static String nullable(Object value) {
+		return value == null ? "" : String.valueOf(value);
+	}
+
+	private static String tsv(String value) {
+		return value == null ? "" : value.replace('\t', ' ').replace('\r', ' ').replace('\n', ' ');
+	}
+
+	private record ObjectConfig(String name, String description, String poClass, String tableName,
+			String idName, String canonicalName, String logicalIndex, List<String> searchFields,
+			List<String> keywordFields, boolean hasFts, boolean root, String childStr, String xmlFile) {
+
+		private List<String> allFields() {
+			Set<String> fields = new LinkedHashSet<>();
+			if (idName != null && !idName.isBlank())
+				fields.add(idName);
+			fields.addAll(searchFields);
+			fields.addAll(keywordFields);
+			return new ArrayList<>(fields);
+		}
+	}
+
+	private static final class RebuildUnit {
+		private final String logicalIndex;
+		private final List<ObjectConfig> sources;
+		private final String canonicalName;
+		private final ObjectConfig canonical;
+		private final List<String> issues = new ArrayList<>();
+		private final List<String> warnings = new ArrayList<>();
+		private Long dbCount;
+		private boolean esExists;
+		private Long esCount;
+
+		private RebuildUnit(String logicalIndex, List<ObjectConfig> sources, String canonicalName, ObjectConfig canonical) {
+			this.logicalIndex = logicalIndex;
+			this.sources = List.copyOf(sources);
+			this.canonicalName = canonicalName;
+			this.canonical = canonical;
+		}
+
+		private boolean blocked() {
+			return !issues.isEmpty();
+		}
+
+		private boolean countMismatch() {
+			return dbCount != null && esCount != null && !dbCount.equals(esCount);
+		}
+
+		private String sourceNames() {
+			return String.join(", ", sources.stream().map(source -> source.name).sorted().toList());
+		}
+
+		private String tableAndId() {
+			return canonical == null ? "" : canonical.tableName + "/" + canonical.idName;
+		}
+
+		private String fields() {
+			return canonical == null ? "" : String.join(", ", canonical.allFields());
+		}
+
+		private String messages() {
+			String issueText = issues.isEmpty() ? "" : "问题:" + String.join(";", issues);
+			String warningText = warnings.isEmpty() ? "" : "警告:" + String.join(";", warnings);
+			return issueText + (issueText.isEmpty() || warningText.isEmpty() ? "" : ";") + warningText;
+		}
+	}
+
+	private record Inventory(int configuredObjectCount, int ftsCandidateCount, int rootCandidateCount,
+			List<RebuildUnit> units, List<String> globalIssues) {
+	}
+
+	private record EsEnvironment(String clusterName, String clusterUuid, String version,
+			String health, boolean hasIk) {
+	}
+
+	private static final class EsProbe {
+		private final String baseUrl;
+		private final String authorization;
+		private final HttpClient client = HttpClient.newBuilder().build();
+
+		private EsProbe(String baseUrl, String user, String password) {
+			this.baseUrl = baseUrl.replaceAll("/+$", "");
+			this.authorization = "Basic " + Base64.getEncoder().encodeToString(
+					(user + ":" + password).getBytes(StandardCharsets.UTF_8));
+		}
+
+		private EsEnvironment readEnvironment() throws Exception {
+			String info = get("/");
+			String healthResponse = get("/_cluster/health");
+			String plugins = get("/_nodes/plugins?filter_path=nodes.*.plugins.name");
+			return new EsEnvironment(jsonString(info, "cluster_name"), jsonString(info, "cluster_uuid"),
+					jsonString(info, "number"), jsonString(healthResponse, "status"),
+					plugins.toLowerCase(Locale.ROOT).contains("analysis-ik"));
+		}
+
+		private boolean indexExists(String index) throws Exception {
+			HttpRequest request = request("/" + encode(index)).method("HEAD", HttpRequest.BodyPublishers.noBody()).build();
+			HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
+			if (response.statusCode() == 404)
+				return false;
+			if (response.statusCode() < 200 || response.statusCode() >= 300)
+				throw new IllegalStateException("HTTP " + response.statusCode() + " checking index " + index);
+			return true;
+		}
+
+		private long indexCount(String index) throws Exception {
+			String response = get("/" + encode(index) + "/_count");
+			return jsonLong(response, "count");
+		}
+
+		private String get(String path) throws Exception {
+			HttpResponse<String> response = client.send(request(path).GET().build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
+			if (response.statusCode() < 200 || response.statusCode() >= 300)
+				throw new IllegalStateException("HTTP " + response.statusCode() + " for GET " + path);
+			return response.body();
+		}
+
+		private HttpRequest.Builder request(String path) {
+			return HttpRequest.newBuilder(URI.create(baseUrl + path))
+					.header("Authorization", authorization)
+					.header("Accept", "application/json");
+		}
+
+		private static String encode(String value) {
+			return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20");
+		}
+
+		private static String jsonString(String json, String field) {
+			Matcher matcher = Pattern.compile(String.format(JSON_STRING.pattern(), Pattern.quote(field))).matcher(json);
+			return matcher.find() ? matcher.group(1) : "未取得";
+		}
+
+		private static long jsonLong(String json, String field) {
+			Matcher matcher = Pattern.compile(String.format(JSON_NUMBER.pattern(), Pattern.quote(field))).matcher(json);
+			if (!matcher.find())
+				throw new IllegalArgumentException("JSON field not found: " + field);
+			return Long.parseLong(matcher.group(1));
+		}
+	}
+}

+ 3 - 3
web/cfg/biz/pxm/pxmhj.serv.xml

@@ -74,9 +74,9 @@
 			<!-- 建全文库。增加。Lin -->
 			<serv name="pxmhj_initFtsMake" desc="准备建全文库" clazz="biz.pxm.PxmhjServ" func="initFtsMake"/>
 			<serv name="pxmhj_sureFtsMake" desc="开始建全文库" clazz="biz.pxm.PxmhjServ" func="sureFtsMake"/>
-			<serv name="pxmhj_initFtsIdxRemakePick" desc="准备重建FTS索引" clazz="biz.pxm.PxmhjServ" func="searchFtsIdx"/>
-			<serv name="pxmhj_initSureFtsIdxRemake" desc="准备确认重建FTS索引" clazz="biz.pxm.PxmhjServ" func="initSureFtsIdxRemake"/>
-			<serv name="pxmhj_sureFtsInxRemake" desc="确认重建FTS索引" clazz="biz.pxm.PxmhjServ" func="sureFtsIdxRemake"/>
+			<serv name="pxmhj_initFtsIdxRemakePick" desc="准备FTS安全重建候选" clazz="biz.pxm.FtsRebuildServ" func="searchFtsRebuildCandidates"/>
+			<serv name="pxmhj_initSureFtsIdxRemake" desc="执行FTS重建只读预检" clazz="biz.pxm.FtsRebuildServ" func="dryRunFtsRebuild"/>
+			<serv name="pxmhj_sureFtsInxRemake" desc="FTS安全重建写入未启用" clazz="biz.pxm.FtsRebuildServ" func="rejectFtsRebuildWrite"/>
 
 			<!-- 建 sys 用户。增加。Lin -->
 			<serv name="pxmhj_sureSysUserMake" desc="开始 sys 用户生成" clazz="biz.pxm.PxmhjServ" func="sureSysUserMake"/>

Plik diff jest za duży
+ 0 - 0
web/page/biz/pxmhj_ftsIdxRemakePick.ss.jsp


+ 66 - 1
web/page/biz/pxmhj_ftsIdxRemakeSure.ss.jsp

@@ -1 +1,66 @@
-<html>
<head>
</head>

<style>
	[index]:before{
		content:attr(index)".";
	}
	td{
		padding:0 1em;
		border-left:1px solid black;
	}
	fieldset{
		border:1px dashed lightgray;
		margin:1em;
		padding:1em 0;
		min-height:10%;
		max-height:40%;
		overflow:auto;
	}
	fieldset table td:first-child{
		display:none;
	}
</style>
<body>
	<div style="height:100%;overflow:auto;">
		<form action="<serv.ss name='pxmhj_sureFtsInxRemake' dest='info' parm='{pxmid:&quot;${pxmid}&quot;,pxmhjid:&quot;${pxmhjid}&quot;,gxid:"${gxid}"}'/>" method="post">
			<div id="container" class="dragList-div">
				<fieldset>
					<legend>即将重建以下的 FTS 索引:</legend>
					<table>
						<rpt.ss name="${hasIdx}" id="has">
							&nbsp;${has.name}(${has.desc}):
							<rpt.ss name="${has.searchFieldList}" id="hasSearchField">
								&nbsp;${hasSearchField.name}(${hasSearchField.desc})
							</rpt.ss>
							<rpt.ss name="${has.keywordFieldList}" id="hasField">
								&nbsp;${hasField.name}(${hasField.desc})
							</rpt.ss>
							<br>
						</rpt.ss>
					</table>
				</fieldset>
				<div align='center' style='color:green'>** 将会删除现有的索引,重建索引,并加载对象数据到索引里 **</div>
			</div>
			<div class="bottom-div">
				<input type="submit" value="确认" onclick="" class="bottom-button"/>
			</div>
		</form>
	</div>
</body>
</html>
+<html>
+<head>
+	<style>
+		.fts-preflight { height: 100%; overflow: auto; padding: 12px; box-sizing: border-box; }
+		.fts-warning { color: #b45f06; border: 1px solid #f2cc8f; background: #fff8e7; padding: 10px; margin-bottom: 12px; }
+		.fts-error { color: #a61b1b; margin-bottom: 10px; }
+		.fts-summary { width: 100%; border-collapse: collapse; margin-bottom: 12px; }
+		.fts-summary th, .fts-summary td { border: 1px solid #d9d9d9; padding: 6px; text-align: left; vertical-align: top; }
+		.fts-summary th { width: 150px; background: #f7f7f7; }
+		.fts-units { width: 100%; min-width: 1180px; border-collapse: collapse; }
+		.fts-units th, .fts-units td { border: 1px solid #d9d9d9; padding: 6px; text-align: left; vertical-align: top; }
+		.fts-units th { background: #f3f6f9; white-space: nowrap; }
+	</style>
+</head>
+<body>
+	<div class="fts-preflight">
+		<div class="fts-warning">
+			本页面仅显示 Dry-run 结果:读取目标项目配置、数据库记录数和 Elasticsearch 状态;没有创建、删除、写入或切换任何索引。
+		</div>
+		<div class="fts-error"><common:write value="${ftsRebuildError}" /></div>
+
+		<table class="fts-summary">
+			<tr><th>预检状态</th><td><common:write value="${ftsRebuildPlan.status}" /></td><th>生成时间</th><td><common:write value="${ftsRebuildPlan.createdAt}" /></td></tr>
+			<tr><th>计划 ID</th><td><common:write value="${ftsRebuildPlan.planId}" /></td><th>校验和</th><td style="word-break:break-all"><common:write value="${ftsRebuildPlan.planChecksum}" /></td></tr>
+			<tr><th>项目</th><td><common:write value="${ftsRebuildPlan.projectName}" /></td><th>环境</th><td><common:write value="${ftsRebuildPlan.environmentName}" /></td></tr>
+			<tr><th>目标数据库</th><td colspan="3"><common:write value="${ftsRebuildPlan.dbFingerprint}" /></td></tr>
+			<tr><th>目标 Elasticsearch</th><td colspan="3"><common:write value="${ftsRebuildPlan.esFingerprint}" /></td></tr>
+			<tr><th>对象配置统计</th><td colspan="3">配置对象 <common:write value="${ftsRebuildPlan.configuredObjectCount}" />;FTS 候选 <common:write value="${ftsRebuildPlan.ftsCandidateCount}" />;根候选 <common:write value="${ftsRebuildPlan.rootCandidateCount}" />;全部逻辑索引 <common:write value="${ftsRebuildPlan.logicalIndexCount}" /></td></tr>
+			<tr><th>本次选择</th><td colspan="3">对象:<common:write value="${ftsRebuildPlan.selectedObjectNamesText}" /><br/>逻辑索引:<common:write value="${ftsRebuildPlan.selectedLogicalIndexCount}" />;目标库记录合计:<common:write value="${ftsRebuildPlan.totalDbCount}" /></td></tr>
+			<tr><th>阻断问题</th><td colspan="3"><common:write value="${ftsRebuildPlan.issuesText}" /></td></tr>
+			<tr><th>全局警告</th><td colspan="3"><common:write value="${ftsRebuildPlan.warningsText}" /></td></tr>
+		</table>
+
+		<div style="overflow:auto;">
+			<table class="fts-units">
+				<thead>
+				<tr>
+					<th>状态</th><th>逻辑索引</th><th>来源对象</th><th>canonical 对象</th>
+					<th>表 / 主键</th><th>索引字段</th><th>目标库数量</th><th>现有索引</th>
+					<th>规划物理索引</th><th>问题 / 警告</th>
+				</tr>
+				</thead>
+				<tbody>
+				<rpt.ss name="${hasIdx}" id="unit">
+					<tr>
+						<td><common:write value="${unit.status}" /></td>
+						<td><common:write value="${unit.logicalIndexName}" /></td>
+						<td><common:write value="${unit.sourceObjectNamesText}" /></td>
+						<td><common:write value="${unit.canonicalObjectName}" />(<common:write value="${unit.canonicalObjectDesc}" />)</td>
+						<td><common:write value="${unit.tableName}" /> / <common:write value="${unit.idFieldName}" /></td>
+						<td><common:write value="${unit.fieldNamesText}" /></td>
+						<td><common:write value="${unit.dbCountText}" /></td>
+						<td><common:write value="${unit.existingIndexText}" /></td>
+						<td><common:write value="${unit.physicalIndexName}" /></td>
+						<td>问题:<common:write value="${unit.issuesText}" /><br/>警告:<common:write value="${unit.warningsText}" /></td>
+					</tr>
+				</rpt.ss>
+				</tbody>
+			</table>
+		</div>
+	</div>
+	<div class="bottom-div">
+		<input type="button" value="关闭" onclick="wd.display.closeDialog();" class="bottom-button"/>
+	</div>
+</body>
+</html>

+ 1 - 1
web/page/sys/bpmDiagHome.ss.jsp

@@ -44,7 +44,7 @@
 				</wd:iterate>
 			</select>
 			--%>
-			<input name="bpmjson" value="" id="selectWorkFlow" placeholder="流程" type="hidden" onchange="workFlowDesigner(this)" style="width: 350px;"/>
+			<input name="bpmjson" value="" id="selectWorkFlow" placeholder="流程" type="hidden" onchange="workFlowDesigner" style="width: 350px;"/>
 <%-- 统一用 ccp。Lin
 				<objp@ss name='bpmjson' cb='jsonBpmByBiz' filter='{biz:&quot;${biz}&quot;}'/> --%>
 			<ccp.ss name="biz_bpmjson"/>

+ 25 - 1
web/ss/GooFlow/jpdl.js

@@ -1605,6 +1605,30 @@ function jpdlFilter(filter){
 function compareNodeData(componentData,allNodes,type){
 		
 		var result=[];
+		var valueExists=function(value){
+			return value!==undefined&&value!==null&&$.trim(String(value))!=="";
+		};
+		var taskMatches=function(node){
+			var componentService=valueExists(componentData.service_name)?String(componentData.service_name):"";
+			var nodeService=valueExists(node.service_name)?String(node.service_name):"";
+			if(componentService||nodeService){
+				return componentService!==""&&nodeService===componentService;
+			}
+
+			var componentName=valueExists(componentData.name)?String(componentData.name):"";
+			var nodeName=valueExists(node.name)?String(node.name):"";
+			if(componentName&&nodeName&&nodeName===componentName){
+				return true;
+			}
+
+			var componentBeforeService=valueExists(componentData.Bservice_name)?String(componentData.Bservice_name):"";
+			var nodeBeforeService=valueExists(node.Bservice_name)?String(node.Bservice_name):"";
+			if(componentBeforeService&&nodeBeforeService){
+				return nodeBeforeService===componentBeforeService;
+			}
+
+			return false;
+		};
 	
 		if(allNodes){
 			
@@ -1613,7 +1637,7 @@ function compareNodeData(componentData,allNodes,type){
 				if(node.realtype!=type)continue;
 				if(type=="end" 
 				||type=="start" ||
-				(type=="task"&&node.service_name==componentData.service_name)){
+				(type=="task"&&taskMatches(node))){
 //					&&node.service_dest==componentData.service_dest
 					var dd={}
 					var ddcount=0;

+ 3 - 2
web/ss/js/lc.js

@@ -29,11 +29,12 @@ function workFlowDesigner(THIS) {
 
 //		var designURL = document.getElementById("workFlowDesignerURL").value 
 //		+ '&fileName=' + selectName + '&thisAppName=' + getURLParam("thisAppName")+"&version="+version;
-		if(!THIS.value)return
+		var workflowValue = typeof THIS === "string" ? THIS : THIS && THIS.value;
+		if(!workflowValue)return
 /* 再改,去掉 thisAppName。Lin
 		var designURL = document.getElementById("workFlowDesignerURL").value
 		 + '&thisAppName=' + getURLParam("thisAppName")+THIS.value
-*/	var designURL = document.getElementById("workFlowDesignerURL").value + THIS.value
+*/	var designURL = document.getElementById("workFlowDesignerURL").value + workflowValue
 
 		
 		page.src = designURL

Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików