Files
NODEDC_PLATFORM/infra/deploy-runner/build-module-foundry-map-runtime-recovery-artifact.mjs

305 lines
8.5 KiB
JavaScript

#!/usr/bin/env node
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import {
cp,
lstat,
mkdir,
mkdtemp,
readdir,
readFile,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const scriptDir = dirname(fileURLToPath(import.meta.url));
const declaredFoundryRoot = process.env.NODEDC_FOUNDRY_SOURCE_ROOT;
if (!declaredFoundryRoot) {
throw new Error("NODEDC_FOUNDRY_SOURCE_ROOT_is_required");
}
const foundryRoot = resolve(declaredFoundryRoot);
const expectedSourceCommit = "58800d957632320fa6717ec3fcff972023528759";
const artifactDir = resolve(
process.env.NODEDC_DEPLOY_ARTIFACT_DIR
|| resolve(scriptDir, "../deploy-artifacts"),
);
const [
patchId = "module-foundry-map-runtime-recovery-20260809-003",
...extra
] = process.argv.slice(2);
if (
extra.length
|| !/^module-foundry-map-runtime-recovery-\d{8}-\d{3}$/.test(patchId)
) {
throw new Error(
"usage: build-module-foundry-map-runtime-recovery-artifact.mjs "
+ "[module-foundry-map-runtime-recovery-YYYYMMDD-NNN]",
);
}
const files = Object.freeze([
"package.json",
"package-lock.json",
"apps/catalog/src",
"packages",
"registry",
"runtime-seed/page-layouts/map.json",
"scripts",
"server/catalog-server.mjs",
"server/foundry-mcp.mjs",
"server/map-grid-persistence.test.mjs",
]);
const ignoredBasenames = new Set([
".DS_Store",
".git",
"node_modules",
"runtime-data",
"dist",
]);
const artifact = join(artifactDir, `nodedc-${patchId}.tgz`);
const checksum = `${artifact}.sha256`;
const stage = await mkdtemp(
join(tmpdir(), "nodedc-foundry-map-runtime-recovery-"),
);
await assertFresh(artifact);
await assertExactSource();
await assertRecoveryBoundary();
try {
for (const sourceRelative of files) {
await copySafe(
resolve(foundryRoot, sourceRelative),
join(stage, "payload", sourceRelative),
);
}
await writeFile(
join(stage, "manifest.env"),
`id=${patchId}\ncomponent=module-foundry\ntype=app-overlay\n`,
"utf8",
);
await writeFile(join(stage, "files.txt"), `${files.join("\n")}\n`, "utf8");
await mkdir(artifactDir, { recursive: true });
run("python3", ["-c", canonicalTarScript(), artifact, stage]);
const sha256 = digest(await readFile(artifact));
await writeFile(
checksum,
`${sha256} ${artifact.split("/").at(-1)}\n`,
"utf8",
);
console.log(JSON.stringify({
ok: true,
patchId,
artifact,
checksum,
sha256,
sourceCommit: expectedSourceCommit,
services: ["nodedc-module-foundry"],
transition: "reconcile-partial-map-source-and-activate-runtime",
files,
}, null, 2));
} finally {
await rm(stage, { recursive: true, force: true });
}
async function assertExactSource() {
const declared = process.env.NODEDC_FOUNDRY_SOURCE_COMMIT;
if (declared !== expectedSourceCommit) {
throw new Error("foundry_source_commit_mismatch");
}
const dotGit = join(foundryRoot, ".git");
try {
await lstat(dotGit);
} catch (error) {
if (error?.code === "ENOENT") return;
throw error;
}
const tracked = spawnSync(
"git",
["-C", foundryRoot, "diff", "--quiet", "HEAD", "--", ...files],
{ encoding: "utf8" },
);
if (tracked.status !== 0) {
throw new Error("foundry_selected_source_is_dirty");
}
const untracked = git(foundryRoot, [
"ls-files",
"--others",
"--exclude-standard",
"--",
...files,
]);
if (untracked) {
throw new Error("foundry_selected_source_has_untracked_files");
}
}
async function assertRecoveryBoundary() {
const packageJson = await readFile(join(foundryRoot, "package.json"), "utf8");
const packageLock = await readFile(
join(foundryRoot, "package-lock.json"),
"utf8",
);
const preview = await readFile(
join(foundryRoot, "apps/catalog/src/MapFixturePreview.tsx"),
"utf8",
);
const renderer = await readFile(
join(foundryRoot, "apps/catalog/src/CesiumMapRenderer.tsx"),
"utf8",
);
const policy = await readFile(
join(foundryRoot, "apps/catalog/src/mapGridPolicy.mjs"),
"utf8",
);
const sector = await readFile(
join(foundryRoot, "apps/catalog/src/mapSectorGrid.mjs"),
"utf8",
);
const server = await readFile(
join(foundryRoot, "server/catalog-server.mjs"),
"utf8",
);
const registry = await readFile(
join(foundryRoot, "registry/registry.json"),
"utf8",
);
for (const marker of [
"@nodedc/map-cesium-react",
"npm run build --workspace @nodedc/map-cesium-react",
]) {
if (!packageJson.includes(marker)) {
throw new Error(`map_package_boundary_missing:${marker}`);
}
}
if (!packageLock.includes('"packages/map-cesium-react"')) {
throw new Error("map_package_lock_boundary_missing");
}
for (const marker of [
"const sectorSpatialEntities = useMemo",
"runtimeBindings={[...sectorScopedPrimaryRuntimeBindings, ...referenceRuntimeBindings]}",
'label="Скрыть объекты за сектором"',
]) {
if (!preview.includes(marker)) {
throw new Error(`map_workspace_boundary_missing:${marker}`);
}
}
for (const marker of [
"class GridLayerController",
"gridLegacyMode",
"viewer.flyTo(entity",
]) {
if (!renderer.includes(marker)) {
throw new Error(`map_renderer_boundary_missing:${marker}`);
}
}
for (const marker of [
"gridLodProfiles",
"GRID_LOD_HYSTERESIS_RATIO",
]) {
if (!policy.includes(marker)) {
throw new Error(`map_policy_boundary_missing:${marker}`);
}
}
for (const marker of [
"export function geodeticToLocalGridPlane",
"export function localSectorAtGeodetic",
]) {
if (!sector.includes(marker)) {
throw new Error(`map_sector_boundary_missing:${marker}`);
}
}
for (const marker of [
"gridLodProfiles",
"validateGridLodProfiles",
]) {
if (!server.includes(marker)) {
throw new Error(`map_server_boundary_missing:${marker}`);
}
}
if (!registry.includes('"@nodedc/map-cesium-react"')) {
throw new Error("map_registry_boundary_missing");
}
}
async function copySafe(source, destination) {
const sourceStat = await lstat(source);
if (sourceStat.isSymbolicLink()) {
throw new Error(
`source_symlink_rejected:${relative(foundryRoot, source)}`,
);
}
if (sourceStat.isFile()) {
await mkdir(dirname(destination), { recursive: true });
await cp(source, destination, { force: true, verbatimSymlinks: true });
return;
}
if (!sourceStat.isDirectory()) {
throw new Error(`source_type_rejected:${relative(foundryRoot, source)}`);
}
await mkdir(destination, { recursive: true });
for (const entry of await readdir(source, { withFileTypes: true })) {
if (
ignoredBasenames.has(entry.name)
|| entry.name.startsWith(".env")
|| entry.name.endsWith(".tsbuildinfo")
) {
continue;
}
const childSource = join(source, entry.name);
const childDestination = join(destination, entry.name);
if (entry.isSymbolicLink()) {
throw new Error(
`source_symlink_rejected:${relative(foundryRoot, childSource)}`,
);
}
await copySafe(childSource, childDestination);
}
}
async function assertFresh(path) {
try {
await lstat(path);
} catch (error) {
if (error?.code === "ENOENT") return;
throw error;
}
throw new Error("artifact_already_exists");
}
function canonicalTarScript() {
return [
"import gzip,io,pathlib,sys,tarfile",
"root=pathlib.Path(sys.argv[2])",
"with open(sys.argv[1],'wb') as out:",
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
" for top in ('manifest.env','files.txt','payload'):",
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
" for x in paths:",
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
].join("\n");
}
function digest(value) {
return createHash("sha256").update(value).digest("hex");
}
function run(command, args) {
const result = spawnSync(command, args, {
encoding: "utf8",
maxBuffer: 128 * 1024 * 1024,
});
if (result.status !== 0) {
throw new Error(`${command}_failed:${result.stderr || result.stdout}`);
}
}