Files
ViewDesignEngine/plugins/external/runner/vde_service_runner.cpp
T
hm 163d0c47e6 feat: P1.x 内核对齐 + P2-1 vde_cae + P2-2 插件扩展点 + VDE-1249 三阻塞修复(1.0.47)
### P1.x 内核对齐(P1 遗留收口)
- 原生 .vde 序列化(serializer/vde_format/vde_text)迁入内核 vde_brep;C API 序列化回迁 vde_kernel_capi;
  PMI/MBD 拆为内核数据模型(vde_brep)+ 3D-PDF 导出(vde_io/pmi_export.cpp),消除 kernel→io 反向依赖;
- make_geometry_host_services() 迁入内核 vde_brep,kernel-only 下 PluginManager+宿主服务可用;
- kernel-only 约 40 个测试 target + 4 个 examples 门控;六业务 OFF 的 2 个测试 target 门控;
- vde_version() 返回 0.5.0 既有缺陷修复;kernel SDK consumer 实测 1.0.47;

### P2-1 vde_cae 官方模块
- include/vde/cae/*、src/cae/*、tests/cae/*;旧路径转发头兼容;VDE_BUILD_CAE 开关;
- vde_io 移除 fea_mesh/fluid_domain;ctest 用例数保持(95 项 CAE 测试);CAE=OFF 构建 937/937;

### P2-2 插件 ABI 1.2:CAE solver / CAM strategy 扩展点
- VdeCaeSolverPlugin/VdeCamStrategyPlugin + Registration 尾部扩展(旧插件兼容);
- PluginManager cae_solvers()/cam_strategies()/solve_cae()/invoke_cam(),加载校验/失败隔离;
- plugins/sample_cae、sample_cam_post、abi11_compat、external/{runner,sample_stl_converter};
- docs/design/vde-service-protocol.md 进程外服务协议草案;test_plugin_extensions 9/9;

### VDE-1249 三阻塞修复
- fix1 共享边采样性能悬崖:sagitta 自适应段数 + 自由曲面证据触发 + fast planar loop 256 + IncrementalMesher 复用 mesh_face_diag;
  box+16 孔 legacy 3.3-3.6s→69.5ms、rebuild 4095→103ms;box+25 孔 5.1s→190.9ms;n42 链 ≤222ms;open=0/面积体积正确;
- fix2 fillet/blend 破损体护栏(fillet_edges_checked:watertight/dangling 护栏 + heal 重试 + 显式失败/诊断;
  静默 no-op success → 显式失败)+ delete_face_with_heal/fill_hole 边环重排(26 面盒 0/26→6/6,box 2/6→6/6);
- fix3 wireframe tight payload:WireframeOptions.include_segment_info + C API VdeWireframeOptions 尾扩展 +
  vde_body_to_wireframe_opt2(旧 ABI 安全);tight≈49-61% full(与 1.0.12 旧风格差 4B/段);

### 工程
- 修复 .gitignore `*.txt` 误伤:`!CMakeLists.txt`,把 plugins/**、tools/、tests/plugin、tests/cae 等漏入库的
  CMakeLists.txt 纳入版本库(保证干净 checkout 可构建);
- 版本 1.0.47(CMake/version.h/test_version/README/docs index/module-manual 同步);

验证:全量构建 0 error(334 targets);全量 ctest 7395 注册、7300/7300 PASS(0 failed,24 skipped,194.39s);
kernel-only(-DVDE_BUILD_IO=OFF + BUILD_TESTS=ON)全量构建 0 failed、plugin 30/12 + capi_split 7 全绿;
六业务 OFF 全量测试构建 0 failed;CAE 95/95;插件 ctest 61/61;VDE-1249 repro 前后数字见 CHANGELOG。
2026-10-28 16:32:01 +08:00

442 lines
17 KiB
C++

// VDE 进程外服务协议(P2 草案)最小 runner。
//
// 职责:
// - 发现服务清单(vde-service.json,递归 2 层);
// - 按清单启动外部服务可执行文件(--request/--response 文件交换);
// - 超时强制终止、退出码/响应状态校验、结果回显。
//
// 退出码(与 docs/design/vde-service-protocol.md 一致):
// 0 = 成功;2 = 用法错误;3 = 清单/协议错误;4 = 超时;5 = 服务失败。
//
// 说明:本 runner 是最小验证实现,不依赖任何 VDE 库;真实宿主应复用同一协议
// 但换成正式进程管理/沙箱实现。
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <chrono>
#include <filesystem>
#include <string>
#include <thread>
#include <vector>
#include "../common/service_common.h"
#ifdef _WIN32
#include <windows.h>
#else
#include <cerrno>
#include <csignal>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
namespace {
namespace fs = std::filesystem;
using namespace vde_service;
constexpr int kExitOk = 0;
constexpr int kExitUsage = 2;
constexpr int kExitProtocol = 3;
constexpr int kExitTimeout = 4;
constexpr int kExitServiceFailed = 5;
std::string platform_entry_key() {
#if defined(_WIN32)
return "windows";
#elif defined(__APPLE__)
return "macos";
#else
return "linux";
#endif
}
std::string quote_arg(const std::string& value) {
std::string out = "\"";
for (char c : value) {
if (c != '"') out.push_back(c);
}
out.push_back('"');
return out;
}
struct Manifest {
std::string id;
std::string name;
std::string version;
std::string protocol;
std::string executable;
std::string manifest_path;
int default_timeout_ms = 30000;
bool valid = false;
std::string error;
};
Manifest load_manifest(const std::string& path) {
Manifest manifest;
manifest.manifest_path = path;
std::string text;
if (!read_file(path, &text)) {
manifest.error = "cannot read service manifest '" + path + "'";
return manifest;
}
manifest.id = find_string(text, "id");
manifest.name = find_string(text, "name");
manifest.version = find_string(text, "version");
manifest.protocol = find_string(text, "version"); // 兼容:protocol.version 由外层解析
// protocol: { "name": "vde-service", "version": "0.1" }:直接取首个 protocol 块后的字段
const std::size_t protocol_pos = text.find("\"protocol\"");
if (protocol_pos != std::string::npos) {
const std::string tail = text.substr(protocol_pos);
const std::string name = find_string(tail, "name");
const std::string version = find_string(tail, "version");
const std::string timeout = std::to_string(static_cast<int>(find_number(tail, "request_ms", 0.0)));
(void)timeout;
if (!name.empty()) manifest.protocol = name + "/" + version;
const double request_ms = find_number(tail, "request_ms", 0.0);
if (request_ms > 0.0) manifest.default_timeout_ms = static_cast<int>(request_ms);
}
const std::size_t entry_pos = text.find("\"executable\"");
if (entry_pos != std::string::npos) {
const std::string tail = text.substr(entry_pos);
manifest.executable = find_string(tail, platform_entry_key());
if (manifest.executable.empty()) manifest.executable = find_string(tail, "windows");
if (manifest.executable.empty()) manifest.executable = find_string(tail, "linux");
}
if (manifest.id.empty()) {
manifest.error = "service manifest missing 'id'";
return manifest;
}
if (manifest.executable.empty()) {
manifest.error = "service manifest missing platform executable entry";
return manifest;
}
manifest.valid = true;
return manifest;
}
struct ProcessResult {
bool started = false;
bool timed_out = false;
int exit_code = -1;
std::string error;
};
ProcessResult run_process(const std::string& command, int timeout_ms) {
ProcessResult result;
#ifdef _WIN32
STARTUPINFOA startup{};
startup.cb = sizeof(startup);
PROCESS_INFORMATION process{};
std::vector<char> command_line(command.begin(), command.end());
command_line.push_back('\0');
if (!CreateProcessA(nullptr, command_line.data(), nullptr, nullptr, FALSE,
CREATE_NO_WINDOW, nullptr, nullptr, &startup, &process)) {
result.error = "CreateProcess failed (error=" + std::to_string(GetLastError()) + ")";
return result;
}
result.started = true;
const DWORD wait = WaitForSingleObject(process.hProcess,
static_cast<DWORD>(timeout_ms < 0 ? 0 : timeout_ms));
if (wait == WAIT_TIMEOUT) {
TerminateProcess(process.hProcess, 4);
WaitForSingleObject(process.hProcess, 5000);
result.timed_out = true;
}
DWORD code = 0;
GetExitCodeProcess(process.hProcess, &code);
result.exit_code = static_cast<int>(code);
CloseHandle(process.hThread);
CloseHandle(process.hProcess);
return result;
#else
const pid_t pid = fork();
if (pid < 0) {
result.error = "fork failed";
return result;
}
if (pid == 0) {
execl("/bin/sh", "sh", "-c", command.c_str(), static_cast<char*>(nullptr));
_exit(127);
}
result.started = true;
const auto deadline =
std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms);
int status = 0;
for (;;) {
const pid_t waited = waitpid(pid, &status, WNOHANG);
if (waited == pid) break;
if (waited < 0) {
result.error = "waitpid failed";
return result;
}
if (std::chrono::steady_clock::now() > deadline) {
kill(pid, SIGKILL);
waitpid(pid, &status, 0);
result.timed_out = true;
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
if (WIFEXITED(status)) result.exit_code = WEXITSTATUS(status);
else result.exit_code = kExitServiceFailed;
return result;
#endif
}
void print_usage() {
std::printf(
"vde_service_runner (VDE external service protocol draft, P2)\n"
"\n"
"Usage:\n"
" vde_service_runner --list <dir>\n"
" scan <dir> (2 levels) for vde-service.json and print discovered services\n"
" vde_service_runner --run --manifest <vde-service.json> (--request <req.json> | --request-json <json>)\n"
" [--workdir <dir>] [--timeout-ms <n>]\n"
" start the service executable with request/response file exchange\n"
" vde_service_runner --abi\n"
" print protocol version\n"
"\n"
"Exit codes: 0 ok, 2 usage error, 3 manifest/protocol error, 4 timeout, 5 service failed.\n");
}
int command_list(const std::string& dir) {
std::error_code ec;
if (!fs::is_directory(dir, ec) || ec) {
std::fprintf(stderr, "[vde-service-runner] error: not a directory: '%s'\n", dir.c_str());
return kExitProtocol;
}
std::vector<fs::path> candidates;
candidates.push_back(dir);
std::vector<fs::path> level1;
for (const auto& entry : fs::directory_iterator(dir, ec)) {
if (ec) break;
if (entry.is_directory()) {
level1.push_back(entry.path());
candidates.push_back(entry.path());
}
}
for (const auto& first : level1) {
for (const auto& entry : fs::directory_iterator(first, ec)) {
if (ec) break;
if (entry.is_directory()) candidates.push_back(entry.path());
}
}
int found = 0;
for (const auto& candidate : candidates) {
const fs::path manifest_path = candidate / "vde-service.json";
std::error_code file_ec;
if (!fs::is_regular_file(manifest_path, file_ec) || file_ec) continue;
const Manifest manifest = load_manifest(manifest_path.string());
if (!manifest.valid) {
std::fprintf(stderr, "[vde-service-runner] skip '%s': %s\n",
manifest_path.string().c_str(), manifest.error.c_str());
continue;
}
++found;
std::string text;
read_file(manifest_path.string(), &text);
std::printf("- id : %s\n", manifest.id.c_str());
std::printf(" name : %s\n", manifest.name.c_str());
std::printf(" version : %s\n", manifest.version.c_str());
std::printf(" protocol : %s\n", manifest.protocol.c_str());
std::printf(" executable : %s\n", manifest.executable.c_str());
std::printf(" timeout_ms : %d\n", manifest.default_timeout_ms);
std::string capabilities;
for (const auto& capability : find_string_array(text, "capabilities")) {
if (!capabilities.empty()) capabilities += "; ";
capabilities += capability;
}
std::printf(" capabilities : %s\n", capabilities.c_str());
std::printf(" manifest : %s\n", manifest_path.string().c_str());
}
std::printf("discovered %d external service manifest(s)\n", found);
return kExitOk;
}
int command_run(const std::string& manifest_path, const std::string& request_file,
const std::string& request_json, const std::string& workdir_override,
int timeout_override_ms) {
if (manifest_path.empty()) {
std::fprintf(stderr, "[vde-service-runner] error: missing --manifest\n");
return kExitUsage;
}
if (request_file.empty() && request_json.empty()) {
std::fprintf(stderr,
"[vde-service-runner] error: need --request <file> or --request-json <json>\n");
return kExitUsage;
}
const Manifest manifest = load_manifest(manifest_path);
if (!manifest.valid) {
std::fprintf(stderr, "[vde-service-runner] error: %s\n", manifest.error.c_str());
return kExitProtocol;
}
const fs::path manifest_dir = fs::path(manifest_path).parent_path();
fs::path executable = fs::path(manifest.executable);
if (executable.is_relative()) executable = manifest_dir / executable;
std::error_code ec;
if (!fs::is_regular_file(executable, ec) || ec) {
std::fprintf(stderr, "[vde-service-runner] error: executable not found: '%s'\n",
executable.string().c_str());
return kExitProtocol;
}
fs::path workdir;
if (!workdir_override.empty()) {
workdir = fs::path(workdir_override);
} else {
workdir = fs::temp_directory_path(ec);
if (ec) workdir = manifest_dir;
}
workdir /= "vde_service_" + std::to_string(
#ifdef _WIN32
static_cast<long long>(GetCurrentProcessId())
#else
static_cast<long long>(getpid())
#endif
) +
"_" + std::to_string(
#ifdef _WIN32
static_cast<long long>(GetTickCount64())
#else
static_cast<long long>(std::chrono::steady_clock::now().time_since_epoch().count())
#endif
);
fs::create_directories(workdir, ec);
if (ec) {
std::fprintf(stderr, "[vde-service-runner] error: cannot create workdir '%s': %s\n",
workdir.string().c_str(), ec.message().c_str());
return kExitProtocol;
}
const fs::path request_path = workdir / "request.json";
const fs::path response_path = workdir / "response.json";
std::string request_text = request_json;
if (!request_file.empty()) {
if (!read_file(request_file, &request_text)) {
std::fprintf(stderr, "[vde-service-runner] error: cannot read request file '%s'\n",
request_file.c_str());
return kExitProtocol;
}
}
if (!write_file(request_path.string(), request_text)) {
std::fprintf(stderr, "[vde-service-runner] error: cannot write request '%s'\n",
request_path.string().c_str());
return kExitProtocol;
}
std::error_code remove_ec;
fs::remove(response_path, remove_ec);
const int timeout_ms = timeout_override_ms > 0 ? timeout_override_ms : manifest.default_timeout_ms;
const std::string command = quote_arg(executable.string()) + " --request " +
quote_arg(request_path.string()) + " --response " +
quote_arg(response_path.string());
const auto begin = std::chrono::steady_clock::now();
const ProcessResult process = run_process(command, timeout_ms);
const double elapsed_ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin).count();
if (!process.started) {
std::fprintf(stderr, "[vde-service-runner] error: cannot start service: %s\n",
process.error.c_str());
return kExitServiceFailed;
}
if (process.timed_out) {
std::fprintf(stderr,
"[vde-service-runner] error: timeout after %.0f ms (limit %d ms), service '%s' killed\n",
elapsed_ms, timeout_ms, manifest.id.c_str());
return kExitTimeout;
}
// 响应优先:即使服务以非 0 退出,只要写了可解析的 response.json,就以响应
// 的 status/code 为准判定(区分「协议/业务错误」与「进程崩溃」)。
std::string response;
const bool has_response = read_file(response_path.string(), &response);
const std::string status = has_response ? find_string(response, "status") : std::string();
const int child_exit = process.exit_code;
if (!has_response || status.empty()) {
if (child_exit != 0) {
std::fprintf(stderr,
"[vde-service-runner] error: service '%s' failed (exit=%d, no response, %.0f ms)\n",
manifest.id.c_str(), child_exit, elapsed_ms);
return kExitServiceFailed;
}
std::fprintf(stderr, "[vde-service-runner] error: service '%s' produced no response file\n",
manifest.id.c_str());
return kExitProtocol;
}
if (status != "ok") {
const std::string code = find_string(response, "code");
const std::string message = find_string(response, "message");
std::fprintf(stderr,
"[vde-service-runner] error: service '%s' status='%s' code='%s' message='%s' exit=%d (%.0f ms)\n",
manifest.id.c_str(), status.c_str(), code.c_str(), message.c_str(),
child_exit, elapsed_ms);
// 服务显式报告协议/业务错误:退出码 3;进程异常退出(非声明错误)归 5。
return (child_exit == 0 || child_exit == kExitProtocol) ? kExitProtocol
: kExitServiceFailed;
}
if (child_exit != 0) {
std::fprintf(stderr,
"[vde-service-runner] error: service '%s' reported ok but exited with code %d (%.0f ms)\n",
manifest.id.c_str(), child_exit, elapsed_ms);
return kExitServiceFailed;
}
std::printf("service=%s protocol=%s status=ok elapsed_ms=%.0f\n", manifest.id.c_str(),
manifest.protocol.c_str(), elapsed_ms);
std::printf("%s\n", response.c_str());
return kExitOk;
}
} // namespace
int main(int argc, char** argv) {
if (argc < 2) {
print_usage();
return kExitUsage;
}
const std::string mode = argv[1];
if (mode == "--help" || mode == "-h") {
print_usage();
return kExitOk;
}
if (mode == "--abi") {
std::printf("vde-service protocol %s/%s\n", protocol_name(), protocol_version());
return kExitOk;
}
if (mode == "--list") {
if (argc < 3) {
print_usage();
return kExitUsage;
}
return command_list(argv[2]);
}
if (mode == "--run") {
std::string manifest_path;
std::string request_file;
std::string request_json;
std::string workdir;
int timeout_ms = 0;
for (int i = 2; i < argc; ++i) {
const std::string arg = argv[i];
const auto next = [&](const char* name) -> std::string {
if (i + 1 >= argc) {
std::fprintf(stderr, "[vde-service-runner] error: %s needs a value\n", name);
std::exit(kExitUsage);
}
return argv[++i];
};
if (arg == "--manifest") manifest_path = next("--manifest");
else if (arg == "--request") request_file = next("--request");
else if (arg == "--request-json") request_json = next("--request-json");
else if (arg == "--workdir") workdir = next("--workdir");
else if (arg == "--timeout-ms") timeout_ms = std::atoi(next("--timeout-ms").c_str());
else {
std::fprintf(stderr, "[vde-service-runner] error: unknown option '%s'\n", arg.c_str());
return kExitUsage;
}
}
return command_run(manifest_path, request_file, request_json, workdir, timeout_ms);
}
std::fprintf(stderr, "[vde-service-runner] error: unknown mode '%s'\n", mode.c_str());
print_usage();
return kExitUsage;
}